Javascript reg ex 仅匹配整个单词,仅由空格绑定
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2951915/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript reg ex to match whole word only, bound only by whitespace
提问by iamnotmad
so I know \bBlah\b will match a whole Blah, however it will also match Blah in "Blah.jpg" I don't want it to. I want to match only whole words with a space on either side.
所以我知道\bBlah\b 会匹配整个Blah,但是它也会匹配“Blah.jpg”中的Blah 我不希望它匹配。我只想将整个单词与两边的空格匹配。
回答by polygenelubricants
You can try: \sBlah\s.
你可以试试:\sBlah\s。
Or if you allow beginning and end anchors, (^|\s)Blah(\s|$)
或者,如果您允许开始和结束锚点, (^|\s)Blah(\s|$)
This will match "Blah"by itself, or each Blahin "Blah and Blah"
这将匹配"Blah"本身,或每个Blah中"Blah and Blah"
See also
也可以看看
- regular-expressions.info/Character classesand Anchors
\sstands for "whitespace character".- The caret
^matches the position before the first character in the string - Similarly,
$matches right after the last character in the string
- 正则表达式.信息/字符类和锚点
\s代表“空白字符”。- 插入符号
^匹配字符串中第一个字符之前的位置 - 类似地,
$在字符串中的最后一个字符之后匹配
Lookahead variant
前瞻变体
If you want to match both Blahin "Blah Blah", then since the one space is "shared" between the two occurrences, you must use assertions. Something like:
如果您想同时匹配Blahin "Blah Blah",那么由于一个空格在两次出现之间是“共享的”,您必须使用断言。就像是:
(^|\s)Blah(?=\s|$)
See also
也可以看看
Capturing only Blah
仅捕获 Blah
The above regex would also match the leading whitespace.
上面的正则表达式也将匹配前导空格。
If you want only Blah, ideally, lookbehind would've been nice:
如果你只想要Blah,理想情况下,lookbehind 会很好:
(?<=^|\s)Blah(?=\s|$)
But since Javascript doesn't support it, you can instead write:
但是由于 Javascript 不支持它,您可以改为编写:
(?:^|\s)(Blah)(?=\s|$)
Now Blahwould be captured in \1, with no leading whitespace.
现在Blah将被捕获\1,没有前导空格。
See also
也可以看看
回答by Peter Kreinz
回答by VoteyDisciple
Try \sBlah\s?—?that will match any form of whitespace on either side.
尝试\sBlah\s?-? 匹配任何形式的任一侧的空格。
回答by Andrew K
(^|\s)Blah(\s|$)should work, however it will also select the spaces, if you just want the word you can do this:
(^|\s)(Blah)(\s|$)and take group 2 ($2 in ruby).
(^|\s)Blah(\s|$)应该可以工作,但是它也会选择空格,如果您只想要这个词,您可以这样做:
(^|\s)(Blah)(\s|$)并选择第 2 组(红宝石 2 美元)。
If want help with a RegEx, checkout: http://www.gskinner.com/RegExr/
如果需要有关 RegEx 的帮助,请查看:http: //www.gskinner.com/RegExr/
回答by bortunac
extracting all words in a string
提取字符串中的所有单词
words_array = str.match(/\b(\w|')+\b/gim) //only single qout allowed


