Reputation: 1488
I am looking for one regex which strictly allows 2 floating point numbers which are comma separated.
Test cases:
0,0
0.021312311323,0
0,0.012312312312
1.1,0.9836373
Regex that I have tried is
^[-+]?([1-8]?\d(\.\d+)?|90(\.0+)?),\s*[-+]?(180(\.0+)?|((1[0-7]\d)|([1-9]?\d))(\.\d+)?)$\D+|\d*\.?\d+
These are latitudes and longitudes but I just want 2 values in these paremeters.
This regex fails in:
-10a, 10a
10a,10b
I would really appreciate any help and guidance.
Upvotes: 2
Views: 88
Reputation: 12707
Your regular expression is almost correct. You should have stopped at $
indicating the end of the string.
const testCases = [ "0,0",
"0.021312311323,0",
"0,0.012312312312",
"1.1,0.9836373",
"-10a, 10a",
"10a,10b"];
const re = /^[-+]?([1-8]?\d(\.\d+)?|90(\.0+)?),\s*[-+]?(180(\.0+)?|((1[0-7]\d)|([1-9]?\d))(\.\d+)?)$/g;
testCases.forEach(tc => {
if(tc.match(re)) {
console.log(" VALID : " + tc );
} else {
console.log("NOT VALID : " + tc);
}
});
Upvotes: 0
Reputation: 626738
Your regex ends with a couple of redundant patterns, you should remove \D+|\d*\.?\d+
after $
. As $
means the end of string, there can be no more text after it, and the \D+|\d*\.?\d+
requires one or more non-digit chars, or just matches any float or integer number with \d*\.?\d+
- this matched your unwelcome strings.
You can use
^([-+]?(?:[1-8]?\d(?:\.\d+)?|90(?:\.0+)?)),\s*([-+]?(?:180(?:\.0+)?|(?:1[0-7]\d|[1-9]?\d)(?:\.\d+)?))$
See the regex demo. Note I converted some capturing groups into non-capturing, so that there remain just two "notional" capturing groups in the pattern.
Details
^
- start of string([-+]?(?:[1-8]?\d(?:\.\d+)?|90(?:\.0+)?))
- Group 1:
[-+]?
- an optional -
or +
(?:[1-8]?\d(?:\.\d+)?|90(?:\.0+)?)
- either a number from 0 to 89 ([1-8]?\d
) and then an optional fractional part ((?:\.\d+)?
) or 90
and then an optional .
followed with one or more 0
chars,\s*
- a comma and 0+ whitespace chars([-+]?(?:180(?:\.0+)?|(?:1[0-7]\d|[1-9]?\d)(?:\.\d+)?))
- Group 2:
[-+]?
- an optional -
or +
(?:180(?:\.0+)?|(?:1[0-7]\d|[1-9]?\d)(?:\.\d+)?)
- either a 180
number followed with an optional .
+ one or more 0
chars, or a number from 0 to 179 and then an optional fractional part$
- end of string.Upvotes: 1