1

Hello guys i want to write a regex to check if a value has only numbers but 0 not to be in first position . for example the value 10 is correct but the value 01 is wrong.

so far i have this mystr.matches("[123456789]+")

4
  • mystr.matches("[1-9]+") Commented Feb 24, 2013 at 16:52
  • 1
    Is 0 a correct number? Commented Feb 24, 2013 at 16:54
  • @LuiggiMendoza I'm asking about 0, just 0 Commented Feb 24, 2013 at 16:56
  • What about floating point numbers, like 10.5? Commented Feb 24, 2013 at 16:59

5 Answers 5

3

Try this:

mystr.matches("^[1-9]\\d*$")
Sign up to request clarification or add additional context in comments.

3 Comments

You need to escape the \ character by using \\.
Thanks, changed it, apparently I have to put in three \ characters in for it to show two.
matches will return true only if entire string matches used regex so there is no need for ^ and $ :). Also try using "{}" key (or Ctrl+K) next time while creating answer to format selected code and you wont have to use tricks like \\\ to get two backslashes :)
2

Proposed solution:

mystr.matches("[1-9]\\d*")

Explanation:

  • [1-9] in the beginning to check if the first digit is between 1 and 9.
  • \\d* to look for any digit (form 0 to 9).

4 Comments

how about 1, 2, 3, 4, 5, 6, 7, 8, 9 ? Should be \\d* no?
when i put 2 i have problem
@user1884030 answer updated. By the way, is 0 a legal input?
This will match anything with a number (1-9) in it.
2

All answers here will validate numbers like 1, 2, 3, ..., 10, 11, ... but in case you want to also include simple 0 but not 00, 01 and so on you can use

mystr.matches("0|[1-9][0-9]*")

Comments

2

I think that one should do the job: "([1-9]+[0-9]*)"

Cheers!

1 Comment

you don't need + in your regex since you have * after [0-9]. Try to avoid catastrophic backtracking
1

You can also use this regex

^(?!0)\d+$ 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.