Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding Plus Sign in Regular Expression

var string = 'abcd+1'; var pattern = 'd+1' var reg = new RegExp(pattern,''); alert(string.search(reg)); 

I found out last night that if you try and find a plus sign in a string of text with a Javascript regular expression, it fails. It will not find that pattern, even though it exists in that string. This has to be because of a special character. What's the best way to find a plus sign in a piece of text? Also, what other characters will this fail on?

like image 429
Justin Helgerson Avatar asked Jan 07 '10 14:01

Justin Helgerson


People also ask

How do you do a plus sign in regex?

A regular expression followed by a plus sign ( + ) matches one or more occurrences of the one-character regular expression. If there is any choice, the first matching string in a line is used. A regular expression followed by a question mark ( ? ) matches zero or one occurrence of the one-character regular expression.

What does +? Mean in regex?

This means it tries to match as few times as possible, instead of trying to match as many times as possible.

What is the function of the asterisk (*) in regular expressions?

The asterisk has no function in regular expressions. Indicates that the preceding character may occur 1 or more times in a proper match.


2 Answers

Plus is a special character in regular expressions, so to express the character as data you must escape it by prefixing it with \.

var reg = /d\+1/; 
like image 157
Quentin Avatar answered Nov 03 '22 06:11

Quentin


\-\.\/\[\]\\ **always** need escaping \*\+\?\)\{\}\| need escaping when **not** in a character class- [a-z*+{}()?] 

But if you are unsure, it does no harm to include the escape before a non-word character you are trying to match.

A digit or letter is a word character, escaping a digit refers to a previous match, escaping a letter can match an unprintable character, like a newline (\n), tab (\t) or word boundary (\b), or a a set of characters, like any word-character (\w), any non-word character (\W).

Don't escape a letter or digit unless you mean it.

like image 27
kennebec Avatar answered Nov 03 '22 06:11

kennebec