gpt4 book ai didi

regex - gsub 的倒数

转载 作者:行者123 更新时间:2023-12-04 16:26:14 28 4
gpt4 key购买 nike

我有一些正在使用的 html 代码。我想提取某些字符串。

我想使用 从字符串 x 中提取它的首选基础 R :coleman_l, SMOG4
这是我所拥有的:

x <- "<code>(hi)<a href=\"Read\">auto</a></code>(coleman_l, SMOG4)<br />Read</li>" 
#remove the string (this works)
gsub("a></code>(.+?)<br", "a></code><br", x)

#> gsub("a></code>(.+?)<br", "a></code><br", x)
#[1] "<code>(hi)<a href=\"Read\">auto</a></code><br />Read</li>"

#attempt to extract that information (doesn't work)
re <- "(?<=a></code>().*?(?=)<br)"
regmatches(x, gregexpr(re, x, perl=TRUE))

错误信息:
> regmatches(x, gregexpr(re, x, perl=TRUE)) 
Error in gregexpr(re, x, perl = TRUE) :
invalid regular expression '(?<=a></code>().*?(?=)<br)'
In addition: Warning message:
In gregexpr(re, x, perl = TRUE) : PCRE pattern compilation error
'lookbehind assertion is not fixed length'
at ')'

enter code here

注意 :标记为正则表达式,但这是 R 特定的正则表达式。

最佳答案

对于这些类型的问题,我会使用反向引用来提取我想要的部分。

x <- 
"<code>(hi)<a href=\"Read\">auto</a></code>(coleman_l, SMOG4)<br />Read</li>"
gsub(".*a></code>(.+?)<br.*", "\\1", x)
# [1] "(coleman_l, SMOG4)"

如果括号也应该删除,请将它们添加到您要匹配的“纯文本”部分,但请记住,它们需要进行转义:
gsub(".*a></code>\\((.+?)\\)<br.*", "\\1", x)
# [1] "coleman_l, SMOG4"

关于regex - gsub 的倒数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14765418/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com