Martyn Ball
Martyn Ball

Reputation: 4885

Regex, match number with hyphen and without

I have got this string [lat:50.000] and I need to get the number out of it, however sometimes it might have a hyphen at the front of it as it could be a minus number.

I have got this regex at the moment [\-]\d+(\.\d{1,10})? however it will only match the number if it has got the hyphen at the front, I need a regex that will match it with and without the hyphen. So I would be left with 50.000 or in some cases -2.000.

Hope this makes sense.

Upvotes: 2

Views: 3355

Answers (5)

Jan
Jan

Reputation: 43169

Yet another one:

(-?\d[\d.,]+)
# - or not (optional)
# followed by at least a digit
# followed by digits, dots and commas

See a demo on regex101.com.

Upvotes: 1

Wilmer
Wilmer

Reputation: 148

Here is a simple expression

\-?\d*\.?\d*

Upvotes: 0

Rion Williams
Rion Williams

Reputation: 76557

A question mark quantifier ? following a character or group will indicate that it is optional :

-?\d+(\.\d{1,10})?

This is the equivalent of using the {0,1} quantifier.

Upvotes: 1

José Castro
José Castro

Reputation: 671

You need a quantifier to state that the hyphen is optional:

[\-]?\d+(\.\d{1,10})?

You can also improve the expression a bit and put the hyphen out of the character class (since it's just one character):

-?\d+(\.\d{1,10})?

Upvotes: 3

Santiago
Santiago

Reputation: 1745

Use this regex: \-?\d+\.\d{1,10}

Upvotes: 1

Related Questions