Javascript正则表达式 - 将句子中的单词与“+”字符匹配

时间:2021-10-14 20:46:42

I am having an issue properly testing this sentence.

我有一个问题正确测试这句话。

"code in c++ and javascript"

“c ++和javascript中的代码”

I want to match c++ and javascript, but not java. I solved not matching java by introducing a word boundary test on both sides \b.

我想匹配c ++和javascript,但不是java。我通过在两侧引入单词边界测试解决了不匹配java的问题。

Javascript正则表达式 - 将句子中的单词与“+”字符匹配

Solved with word boundary test.

解决了单词边界测试。

Javascript正则表达式 - 将句子中的单词与“+”字符匹配

Now the issue - The same approach is not working with "c++", although it seems to me it should be. Is there something I am missing?

现在问题 - 同样的方法不适用于“c ++”,虽然在我看来它应该是。有什么我想念的吗?

Javascript正则表达式 - 将句子中的单词与“+”字符匹配

And without word boundary

没有字边界

Javascript正则表达式 - 将句子中的单词与“+”字符匹配

3 个解决方案

#1


3  

Since + is not considered a word character, having a \b after + won't work.

由于+不被视为单词字符,因此在+之后使用\ b将不起作用。

You can fix your regex by using a negative lookahead instead of \b on RHS:

你可以在RHS上使用负前瞻而不是\ b修复你的正则表达式:

/\bc\+\+(?!\w)/

RegEx Demo

To match both java and c++ in alternation:

要在交替中匹配java和c ++:

/\b(?:c\+\+|java)(?!\w)/

#2


2  

Are you trying to match both with the same regex? Or independently? This will match c++ if that's what you need:

您是否尝试使用相同的正则表达式进行匹配?还是独立?这将匹配c ++,如果这是你需要的:

c\+{2}

#3


1  

For c++ you can try below

对于c ++,您可以尝试下面

/c\+{2}$/

#1


3  

Since + is not considered a word character, having a \b after + won't work.

由于+不被视为单词字符,因此在+之后使用\ b将不起作用。

You can fix your regex by using a negative lookahead instead of \b on RHS:

你可以在RHS上使用负前瞻而不是\ b修复你的正则表达式:

/\bc\+\+(?!\w)/

RegEx Demo

To match both java and c++ in alternation:

要在交替中匹配java和c ++:

/\b(?:c\+\+|java)(?!\w)/

#2


2  

Are you trying to match both with the same regex? Or independently? This will match c++ if that's what you need:

您是否尝试使用相同的正则表达式进行匹配?还是独立?这将匹配c ++,如果这是你需要的:

c\+{2}

#3


1  

For c++ you can try below

对于c ++,您可以尝试下面

/c\+{2}$/