Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if at least one of two subexpressions in a regular expression match?

Tags:

syntax

regex

I am trying to match floating-point decimal numbers with a regular expression. There may or may not be a number before the decimal, and the decimal may or may not be present, and if it is present it may or may not have digits after it. (For this application, a leading +/- or a trailing "E123" is not allowed). I have written this regex:

/^([\d]*)(\.([\d]*))?$/

Which correctly matches the following:

1
1.
1.23
.23

However, this also matches empty string or a string of just a decimal point, which I do not want.

Currently I am checking after running the regex that $1 or $3 has length greater than 0. If not, it is not valid. Is there a way I can do this directly in the regex?

like image 513
Kip Avatar asked Oct 06 '08 13:10

Kip


1 Answers

I think this will do what you want. It either starts with a digit, in which case the decimal point and digits after it are optional, or it starts with a decimal point, in which case at least one digit is mandatory after it.

/^\d+(\.\d*)?|\.\d+$/
like image 139
Andru Luvisi Avatar answered Nov 11 '22 13:11

Andru Luvisi