Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the regex for “Any positive integer, excluding 0” [duplicate]

There is already an other post for this but i can't comment on it. Sorry for that.

I used

var pattern = new RegExp('^[1-9]\d*$'); 
var result = fieldValue.search(pattern);

but i get a "-1" if I put 12

It allows me just number from 1 to 9 and no more.

Is there something wrong?

like image 311
Pierre Avatar asked May 08 '15 04:05

Pierre


People also ask

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.

What does the regex 0 9 ]+ do?

In this example, [0-9] matches any SINGLE character between 0 and 9 (i.e., a digit), where dash ( - ) denotes the range. The + , known as occurrence indicator (or repetition operator), indicates one or more occurrences ( 1+ ) of the previous sub-expression. In this case, [0-9]+ matches one or more digits.

What does (? I do in regex?

E.g. (? i-sm) turns on case insensitivity, and turns off both single-line mode and multi-line mode.

Is used for zero or more occurrences in regex?

A regular expression followed by an asterisk ( * ) matches zero or more occurrences of the regular expression. If there is any choice, the first matching string in a line is used.


2 Answers

Assuming the language is JavaScript, you need to escape the backslash character within a string for it to have a value of backslash:

'\d' is a string with a value of d
'\\d' is a string with a value of \d

var pattern = new RegExp('^[1-9]\\d*$');

JavaScript also has regular expression literals, which avoid the need for additional escape characters:

var pattern = /^[1-9]\d*$/;
like image 82
zzzzBov Avatar answered Sep 23 '22 22:09

zzzzBov


If you wanted to extend this to allow for positive integers with leading zeros, you could do this:

var pattern = /^\d*[1-9]+\d*$/

This will allow 001 as a valid input (which it is), while not allowing 000 (which is not non zero).

like image 41
Vamshi Ponnapalli Avatar answered Sep 22 '22 22:09

Vamshi Ponnapalli