您可以使用"\b" + targetword + "\b"
,这将在大多数情况下工作,但是这将字符串Sarah's car is broken
在这个词donald
,并在串O'Donald
或匹配Sarah
匹配。
我会使用外表屁股,并期待aheads验证
- 前面的字符是空格,串的开始,或可接受的标点符号
- 尾随字符是空格,串的端部,或可接受的标点符号
这些允许的字符可根据您的实际使用情况。
"(?<=[\s",.]|^)" + targetword + "(?=[\s",.\r\n]|$)"
![enter image description here](https://i.stack.imgur.com/NwoYb.png)
NODE EXPLANATION
--------------------------------------------------------------------------------
(?<= look behind to see if there is:
--------------------------------------------------------------------------------
[\s",.] any character of: whitespace (\n, \r,
\t, \f, and " "), '"', ',', '.'
--------------------------------------------------------------------------------
| OR
--------------------------------------------------------------------------------
^ the beginning of the string
--------------------------------------------------------------------------------
) end of look-behind
--------------------------------------------------------------------------------
targetword 'targetword'
--------------------------------------------------------------------------------
(?= look ahead to see if there is:
--------------------------------------------------------------------------------
[\s",.\r\n] any character of: whitespace (\n, \r,
\t, \f, and " "), '"', ',', '.', '\r'
(carriage return), '\n' (newline)
--------------------------------------------------------------------------------
| OR
--------------------------------------------------------------------------------
$ before an optional \n, and the end of
the string
--------------------------------------------------------------------------------
) end of look-ahead
我实现了这个解决方案。 这个正则表达式结合我的链接功能实际上完全剥离了领先空间,但我设法通过在链接创建功能上添加空间来解决这个问题。 –