Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to allow numbers, plus symbol, minus symbol and brackets

I am trying to create a regex that allows only the following 0-9, plus symbol, minus symbol and brackets (). No limitations on length of each of the mentioned. So far I have this but it does not seem to work.

/^[0-9 -+]+$/
like image 972
user2847098 Avatar asked Jun 03 '15 11:06

user2847098


People also ask

What do the [] brackets mean in regular expressions?

Square brackets ( “[ ]” ): Any expression within square brackets [ ] is a character set; if any one of the characters matches the search string, the regex will pass the test return true.

How do you add a plus sign in regex?

Easy way to make it : " [\+] " this is the alphabet. You may want all plus signs, then " [\+]* " .

What does ?= * Mean in regex?

is a positive lookahead, a type of zero-width assertion. What it's saying is that the captured match must be followed by whatever is within the parentheses but that part isn't captured. Your example means the match needs to be followed by zero or more characters and then a digit (but again that part isn't captured).

How do you write brackets in regex?

[[\]] will match either bracket. In some regex dialects (e.g. grep) you can omit the backslash before the ] if you place it immediately after the [ (because an empty character class would never be useful): [][] .


1 Answers

This should work for you:

^[\d\(\)\-+]+$

^ -> start of string

\d -> same as [0-9]

+ -> one or more repetitions

$ -> end of string

DEMO

var re = /^[\d\(\)\-+]+$/m; 
var str = ['09+()1213+-','fa(-ds'];
var m;
var result = "";
 
for(var i = 0; i < str.length; i++) {
    if ((m = re.exec(str[i])) !== null) {
        if (m.index === re.lastIndex) {
            re.lastIndex++;
        }
        // View your result using the m-variable.
        // eg m[0] etc.
 
    }
  result += "\""+str[i]+  "\"" + " is matched:" + (m != null) + "</br>";
}

document.getElementById("results").innerHTML = result
<div id="results"></div>
like image 174
emartinelli Avatar answered Oct 14 '22 08:10

emartinelli