我正在尝试创建一个正则表达式,用于检查句子中是否存在单词,当且仅当它没有用单引号括起来时。
我尝试了不同的正则表达式,例如:
(?<!' )(?i:THEN)|(?i:THEN)(?! ')
匹配&#39;然后&#39; | &#39;然后&#39;,这不应该匹配。
(?<!' )(?i:THEN)(?! ') or (?<!(' ))(?i:THEN)|(?i:THEN)(?!( '))
匹配&#39;然后&#39;哪个不匹配
我真的被困住,因为我不知道哪个Regex有效。我也试过其他正则表达但它无法匹配:
' then I jumped.
He said then 'Wow'.
非常感谢一些意见!
谢谢!
答案 0 :(得分:1)
此正则表达式将匹配未被引号括起的单词then
。
\bTHEN\b(?<!'\s*THEN(?=\s*'))
有些语言不允许在外观内部进行\s?
或\s*
等交替。因此,如果您正在使用其中一种语言,那么您需要获得有关测试空间的切割器。
\bTHEN\b(?<!'\sTHEN(?=\s'))(?<!'THEN(?='))
现场演示
https://regex101.com/r/gS4zU8/1
then matched
'then matched
then' matched
'then'
' then matched
then ' matched
' then '
' then I jumped. matched
He said then 'Wow'. matched
SthenS
NODE EXPLANATION
----------------------------------------------------------------------
\b the boundary between a word char (\w) and
something that is not a word char
----------------------------------------------------------------------
THEN 'THEN'
----------------------------------------------------------------------
\b the boundary between a word char (\w) and
something that is not a word char
----------------------------------------------------------------------
(?<! look behind to see if there is not:
----------------------------------------------------------------------
' '\''
----------------------------------------------------------------------
\s whitespace (\n, \r, \t, \f, and " ")
----------------------------------------------------------------------
THEN 'THEN'
----------------------------------------------------------------------
(?= look ahead to see if there is:
----------------------------------------------------------------------
\s whitespace (\n, \r, \t, \f, and " ")
----------------------------------------------------------------------
' '\''
----------------------------------------------------------------------
) end of look-ahead
----------------------------------------------------------------------
) end of look-behind
----------------------------------------------------------------------
(?<! look behind to see if there is not:
----------------------------------------------------------------------
'THEN '\'THEN'
----------------------------------------------------------------------
(?= look ahead to see if there is:
----------------------------------------------------------------------
' '\''
----------------------------------------------------------------------
) end of look-ahead
----------------------------------------------------------------------
) end of look-behind
----------------------------------------------------------------------