简体   繁体   中英

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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