简体   繁体   English

带有特殊字符 (.) javascript 的 RegExp 字边界

[英]RegExp word boundary with special characters (.) javascript

I want to find "USA" (without the quotes) if it is in a string as a whole word.我想找到“USA”(不带引号),如果它作为一个完整的词在一个字符串中。

So good strings should be所以好的弦应该是

U.S.A.
u.s.a.
U.S.A. is a great country
Is this U.S.A. ?

Bad string is坏字符串是

U.S.A.mnop
U.S.A

I tried using我尝试使用

/\bU\.S\.A\.\b/i

But strangely the one that works is - (But it fails for other countries and so not useful)但奇怪的是,有效的方法是 - (但它对其他国家无效,因此没有用)

/\bU\.S\.A\.\B/i

This seems opposite of my understanding from documentation and have searched this and there are lots of similar problems but none of them helped me understand the issue.这似乎与我对文档的理解相反,并且已经搜索了这个并且有很多类似的问题,但没有一个帮助我理解这个问题。 I think that the last "."我认为最后一个“。” is being consumed by \\b and hence not working but am still confused.正在被 \\b 消耗,因此无法正常工作,但我仍然感到困惑。

Can someone please help with explanation and the right search string ?有人可以帮忙解释和正确的搜索字符串吗? It should also do proper word search of other strings without special characters.它还应该对没有特殊字符的其他字符串进行适当的单词搜索。

You can check for the word boundary first (as you were doing), but the tricky part is at the end where you can't use the word boundary because of the .您可以首先检查单词边界(正如您所做的那样),但棘手的部分是在最后您不能使用单词边界,因为. . . However, you can check for a whitespace character at the end instead:但是,您可以在末尾检查空格字符:

/\b(u\.s\.a\.)(?:\s|$)/gi

Check out the Regex101查看Regex101

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM