user1022241
user1022241

Reputation:

Regex to match these number rules

In Java, I'm currently using

str.matches("\\d")

but its only matching a single number.

I need to match ints and doubles, e.g. :

"1"
"1337"
".1"
"13.7"

Any help would be awesome.

Upvotes: 3

Views: 197

Answers (6)

MahdeTo
MahdeTo

Reputation: 11184

((\+|-)?(\d+(\.\d+)?|\.\d+))

This would match positive and negative ints, doubles that start with a digit, and doubles start with a dot

Upvotes: 2

rayfranco
rayfranco

Reputation: 3690

I think this regular expression can help you

\\d*\\.?\\d+

Upvotes: 5

tchrist
tchrist

Reputation: 80384

This will match any real number that the Java compiler will recognize. To do this, it also handles things like signed numbers and exponentials. It’s in Pattern.COMMENTS mode because I think anything else is barbaric.

(?xi)                      # the /i is for the exponent
(?:[+-]?)                  # the sign is optional
(?:(?=[.]?[0123456789])
   (?:[0123456789]*)
   (?:(?:[.])
      (?:[0123456789]{0,})
   ) ?
)
# this is where the exponent starts, if you want it
(?:(?:[E])
   (?:(?:[+-]?)
      (?:[0123456789]+)
   ) 
   |
)

Upvotes: 1

gnomed
gnomed

Reputation: 5565

I think this is tidier to look at than the other suggestions, while still doing the same thing.

(\\d+)?(\\.)?\\d+

Upvotes: 1

Johan Kaving
Johan Kaving

Reputation: 4939

There is a quite extensive lesson about regular expressions in the Java Tutorials.

For information about matching multiple characters you should read the section about quantifiers.

Upvotes: -1

gintas
gintas

Reputation: 2178

You can try this regexp:

 ^(\d+(\.\d+)?|\.\d+)$

Upvotes: 5

Related Questions