5

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?

Pierre
  • 675
  • 1
  • 8
  • 18
  • 1
    Please tag the language, I assume this is JavaScript, is that correct? – zzzzBov May 08 '15 at 04:31
  • Use regex literal please. You need to escape ``\`` if you use constructor with string literal. – nhahtdh May 08 '15 at 04:32
  • Ah ok nhahtdh :) that was y mistake.. :( – Pierre May 08 '15 at 04:47
  • Yes zzzzBov it's javascript – Pierre May 08 '15 at 04:48
  • @Wiktor Stribiżew why did you mark my question as duplicate with this question? I didn't ask for why it needs to be double escape but what is the regex of a positive number, someone answer that I needed to escape but when I asked my question in 2015 I didn't know that obviously ;) Your link help to understand the mistake I made in the past but doesn't reply directly to the question asked. Thanks – Pierre Jan 14 '19 at 04:42

2 Answers2

11

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*$/;
zzzzBov
  • 174,988
  • 54
  • 320
  • 367
4

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).