Why this regex '^[0-9]+\.?[0-9]*$'
match for 12.2 and 12,2 ?
jsFiddle
var dot = '12.2', comma = '12,2', regex = '^[0-9]+\.?[0-9]*$'; alert( dot.match(regex) ); alert( comma.match(regex) );
While it works on regexpal.com
In regular expressions, the dot or period is one of the most commonly used metacharacters. Unfortunately, it is also the most commonly misused metacharacter. The dot matches a single character, without caring what that character is. The only exception are line break characters.
Yes, the dot regex matches whitespace characters when using Python's re module.
The dot( . ) matches any character except the newline character. Use the s flag to make the dot ( . ) character class matches any character including the newline.
(dot) metacharacter, and can match any single character (letter, digit, whitespace, everything). You may notice that this actually overrides the matching of the period character, so in order to specifically match a period, you need to escape the dot by using a slash \.
Because the variable regex
is a string the escape sequence \.
is just .
, which matches any character (except newline). If you change the definition of regex to use RegExp literal syntax or escape the escape character (\\.
) then it will work as you expect.
var dot = '12.2' , comma = '12,2' , regex = /^[0-9]+\.?[0-9]*$/; // or '^[0-9]+\\.?[0-9]*$' alert(dot.match(regex)); alert(comma.match(regex));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With