How to check if at least one of the two subexpressions in a regular expression matches?

I am trying to match regex decimal floating point numbers. There may or may not be a number before the decimal, and the decimal may or may not be, and if it is present, it may or may not have digits after it. (Invalid +/- or final "E123" master for this application). I wrote this regular expression:

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

Which correctly matches the following:

 1 1. 1.23 .23 

However, this also corresponds to an empty string or only a decimal point string that I don't want.

I am currently checking after starting a regular expression that $ 1 or $ 3 has a length greater than 0. If not, this is not true. Is there a way I can do this directly in regex?

+7
syntax regex
source share
3 answers

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

 /^\d+(\.\d*)?|\.\d+$/ 
+6
source share

A very late answer, but I would like to answer taken from regular-expressions.info

 [-+]?[\d]*\.?[\d]+? 

Refresh . This [\d]*\.?[\d]+?|[\d]+\. help you pick up 1.

http://regex101.com/r/lJ7fF4/7

+1
source share

Create a regex for each case and OR. Then you only need to check if the expression matches.

 /^(\d+(\.\d*)?)|(\d*\.\d+)$/ 
0
source share

All Articles