Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex javascript, why dot and comma are matching for \

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

like image 821
canardman Avatar asked Mar 29 '11 08:03

canardman


People also ask

What does regex dot match?

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.

Does dot match space in regex?

Yes, the dot regex matches whitespace characters when using Python's re module.

What is the dot or period character used for in JavaScript?

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.

How do you escape a dot in regex?

(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 \.


1 Answers

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)); 
like image 98
maerics Avatar answered Oct 12 '22 18:10

maerics