techguy18985
techguy18985

Reputation: 474

java regex for validating a string?

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]+")

Upvotes: 1

Views: 152

Answers (5)

Trinimon
Trinimon

Reputation: 13957

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

Cheers!

Upvotes: 2

Pshemo
Pshemo

Reputation: 124215

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]*")

Upvotes: 2

Anirudha
Anirudha

Reputation: 32787

You can also use this regex

^(?!0)\d+$ 

Upvotes: 1

Sophie
Sophie

Reputation: 800

Try this:

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

Upvotes: 3

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85779

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

Upvotes: 2

Related Questions