我正在尝试创建一个正则表达式,当且仅当该单词未用单引号引起来时检查句子中是否存在单词。
我尝试过不同的正则表达式,例如:
(?<!' )(?i:THEN)|(?i:THEN)(?! ')
Run Code Online (Sandbox Code Playgroud)
匹配 'then ' | 'then',它不应该匹配。
(?<!' )(?i:THEN)(?! ') or (?<!(' ))(?i:THEN)|(?i:THEN)(?!( '))
Run Code Online (Sandbox Code Playgroud)
匹配不应匹配的“then”
我真的很困惑,因为我不知道哪个正则表达式有效。我也尝试过其他正则表达式,但它无法匹配:
' then I jumped.
He said then 'Wow'.
Run Code Online (Sandbox Code Playgroud)
一些意见将不胜感激!
谢谢你!
then该正则表达式将匹配未用引号引起来的单词。
\bTHEN\b(?<!'\s*THEN(?=\s*'))
Run Code Online (Sandbox Code Playgroud)

有些语言不允许交替,例如\s?或\s*内部回顾。因此,如果您使用其中一种语言,那么您需要深入了解空格测试。
\bTHEN\b(?<!'\s*THEN(?=\s*'))
Run Code Online (Sandbox Code Playgroud)

现场演示
https://regex101.com/r/gS4zU8/1
\bTHEN\b(?<!'\sTHEN(?=\s'))(?<!'THEN(?='))
Run Code Online (Sandbox Code Playgroud)
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
----------------------------------------------------------------------
Run Code Online (Sandbox Code Playgroud)