匹配字符串,但前提是没有其他字符串 [英] Match string, but only if not preceded by other string
问题描述
v = c(SPX.Close,AAPL.Low, Lo,LowPrice,PriceLow,low)
如何编写正则表达式会匹配所有类似短语low的字符串?
grep(lo,v,ignore.case = T)#1 2 3 4 5 6 7
这也匹配第一个字符串,我不想要。
如何匹配 lo
仅在前面加字母 c
?
grep((?<!c)lo,subject,perl = TRUE,value = TRUE, ignore.case = TRUE);
负面后视(?
c
选项2:检查资本Letter,打开不区分大小写内联
考虑到您的输入,更常用的选项是断言 lo
前面没有大写字母:
grep((?<![AZ])(? i)lo,subject,perl = TRUE,value = TRUE);
对于这个选项,我们使用内联修饰符 参考 Say I have vector of strings: How to write regex that would match all strings resembling phrase "low"? This matches the first string too, which I don't want. How to match R uses the PCRE engine, which supports lookbehind. Do this: The negative lookbehind Option 2: Check for Capital Letter, Turn On Case-Insensitivity Inline Given your input, a more general option would be to assert that For this option, we use the inline modifier Reference 这篇关于匹配字符串,但前提是没有其他字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!(?i) code>打开不区分大小写,但是只有在我们检查过没有大写字母在我们的位置之前。
v = c("SPX.Close", "AAPL.Low", "Lo", "LowPrice", "PriceLow", "low")
grep("lo", v, ignore.case=T) # 1 2 3 4 5 6 7
lo
only if not preceded by letter c
?Negative Lookbehind (PCRE in R)
grep("(?<!c)lo", subject, perl=TRUE, value=TRUE, ignore.case=TRUE);
(?<!c)
asserts that what precedes the current position is not a c
lo
is not preceded by a capital letter:grep("(?<![A-Z])(?i)lo", subject, perl=TRUE, value=TRUE);
(?i)
to turn on case-insensitivity, but only after we have checked that no capital letters precede our position.