RegExp带有特殊字符(。)javascript的单词边界 [英] RegExp word boundary with special characters (.) javascript

查看:104
本文介绍了RegExp带有特殊字符(。)javascript的单词边界的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想找到美国。 (如果它在一个字符串中作为整个单词)。

I want to find "U.S.A." (without the quotes) if it is in a string as a whole word.

所以好的字符串应该是

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

错误的字符串是

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

我尝试使用

/\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

这似乎与我对文档的理解相反,并且搜索了这个并且存在许多类似的问题,但它们都没有帮助我理解这个问题。我认为最后一个。正在被\ b消耗,因此无法正常工作但仍然感到困惑。

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

查看< a href =https://regex101.com/r/9TVuPn/4 =nofollow noreferrer> Regex101

这篇关于RegExp带有特殊字符(。)javascript的单词边界的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆