6

I read a lot of regex question, but I didn't find this yet..

I want a regex in Java to check whether a string (no limit to length) is a number:

  • including negative (-4/-123)

  • including 0

  • including positive (2/123)

  • excluding + (+4/+123)

  • excluding leading zero 0 (05/000)

  • excluding . (0.5/.4/1.0)

  • excluding -0

This is what I have done so far:

^(?-)[1-9]+[0-9]*
5
  • 3
    Please show us what you've got so far, and we'll help you along. Commented Dec 13, 2016 at 18:40
  • Code requests aren't valid questions Commented Dec 13, 2016 at 18:42
  • Thanks! - ^(?-)[1-9]+[0-9]* Commented Dec 13, 2016 at 18:43
  • sorry, by "exclude +" do you mean 1) do not consider this a legitimate number, that is, +4 is NOT a number; or 2) do not include the + symbol in the resulting value, that is, +4 is really the number 4? only the first option makes any sense with the 0.5 example, but it seems odd that these legitimate numbers are being excluded. do you really mean, determine if the number is an integer? careful with the terminology, all of those examples are indeed numbers... Commented Dec 13, 2016 at 18:53
  • @ryonts excluding the sign +. which make the number +4 illegal:) Commented Dec 13, 2016 at 18:56

1 Answer 1

13

The is a optional -

-?

The number must not start with a 0

[1-9]

it may be followed by an arbitraty number of digits

\d*

0 is an exception to the "does not start with 0 rule", therefore you can add 0 as alternative.

Final regex

-?[1-9]\d*|0

java code

String input = ...

boolean number = input.matches("-?[1-9]\\d*|0");
Sign up to request clarification or add additional context in comments.

1 Comment

For this kind of answers it was worth building stackoverflow. Detailed, accurate, and demonstrates. You're awesome!!

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.