[英]RegEx for match whole word in sentences - javascript
Trying to work out what the right RegEx would be for finding "s***" in a series of strings, eg:试图找出在一系列字符串中查找“s***”的正确正则表达式是什么,例如:
match for "find s*** in s*** foobar"
match for "s***"
don't match for "s******"
don't match for "s****** foobar"
I'm using a match because I want to count the number of instances of matches in the sentence.我使用匹配是因为我想计算句子中匹配实例的数量。 I was trying "s*{3}" as a starting point, and variations on $ and \\b or \\B but I can't quite figure it out.
我试图将“s*{3}”作为起点,以及 $ 和 \\b 或 \\B 的变体,但我无法弄清楚。
I created some tests here to try it out, if that's helpful.我在这里创建了一些测试来尝试一下,如果有帮助的话。
https://regex101.com/r/VdLyOY/2 https://regex101.com/r/VdLyOY/2
You may use this regex with a negative lookahead:您可以使用此正则表达式进行负面预测:
/\bs\*{3}(?!\*)/g
or with a positive lookahead:或积极展望:
/\bs\*{3}(?=\s|$)/g
RegEx Details:正则表达式详情:
\\bs
: Match letter s
after a word bounday \\bs
: 在单词边界后匹配字母s
\\*{3}
: Match *
3 times ie ***
\\*{3}
: 匹配*
3 次,即***
(?!\\*)
: Negative lookahead to assert that we don't have a *
ahead (?!\\*)
:否定前瞻断言我们没有*
前瞻(?=\\s|$)
: Positive lookahead to assert that we have a whitespace or line end at next position (?=\\s|$)
:正向前瞻断言我们在下一个位置有一个空格或行尾Use用
/\bs\*{3}\B(?!\*)/g
EXPLANATION解释
EXPLANATION
--------------------------------------------------------------------------------
\b the boundary between a word char (\w) and
something that is not a word char
--------------------------------------------------------------------------------
s 's'
--------------------------------------------------------------------------------
\*{3} '*' (3 times)
--------------------------------------------------------------------------------
\B the boundary between two word chars (\w)
or two non-word chars (\W)
--------------------------------------------------------------------------------
(?! look ahead to see if there is not:
--------------------------------------------------------------------------------
\* '*'
--------------------------------------------------------------------------------
) end of look-ahead
/\\bs\\*{3}(\\s|$)/g
可能会起作用,具体取决于您的标准是什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.