Wade Anderson
Wade Anderson

Reputation: 2519

Javascript regex - matching word in sentence with "+" character

I am having an issue properly testing this sentence.

"code in c++ and 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.

image

Solved with word boundary test.

image

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?

image

And without word boundary

image

Upvotes: 4

Views: 240

Answers (3)

Tanvi B
Tanvi B

Reputation: 1567

For c++ you can try below

/c\+{2}$/

Upvotes: 1

anubhava
anubhava

Reputation: 785058

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

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

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

RegEx Demo

To match both java and c++ in alternation:

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

Upvotes: 3

sma
sma

Reputation: 9597

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

c\+{2}

Upvotes: 2

Related Questions