JMD
JMD

Reputation: 339

Regular Expressions: Dealing with + (Plus) Sign

I am a little confused with regular expressions. My intent in below example is to replace all 'NE_NS+' with 'NE_OS+_OE_NS'.When I am giving below code, I don't see any issue with replace results

tempString1 = tempString1.replace (/\NE__NS_+/g,'NE__OS_+_OE__NS_');

When I am giving below code, I see that there are issues. My intent here is to replace all < mn+> with < mn> [No space between < and m]

tempString2 = tempString2.replace (/\<mn>+/g,'<mn>');

and right code for above replace seems to be

tempString3 = tempString3.replace (/\<mn>\+/g,'<mn>');

Why is '+' not relevant in replace example of tempString1 while it is relevant in tempString2 example and wont work until I change it as per code in tempString3?

I have tough time understanding regex. Any books/articles that can help me understand them. I am a novice at regular expression.

Upvotes: 1

Views: 448

Answers (1)

Stephan
Stephan

Reputation: 43013

The problem

Let's take a closer look at your various regexes. You'll understand what's going on:

  • tempString1 \NE__NS_+

Regular expression visualization

Clearly, one or more _ are expected at the end.

  • tempString2 \<mn>+

Regular expression visualization

The \ is simply ignored because it is an escape character. Moreover, it used before < that's don't need to be escaped. Again, > are expected one or more times.

  • tempString3 \<mn>\+

Regular expression visualization

Here the + is escaped, indicating that it is not a meta-character but the plus sign that has to be matched from your temporary string.


The solution

To sum it up, if you want to match NE_NS+, the plus sign must be escaped. So your regex will be:

NE_NS\+

Regular expression visualization

If you want to match < mn+>, you'll use \s for matching a blank character (space, tabulation, carriage return etc). Again, you must escape + since it's a meta character. So, you end up with:

<\smn\+>

Regular expression visualization


There is more...

Use the powerful Debuggex to visualize your regex.

Secondly, use Regexr to quickly live test your regex against a given input text.

Upvotes: 2

Related Questions