Regular expression does not work with javascript

I have a regex that works on regexplib.com when I test it using the .NET engine. It does not match JavaScript. I also tried JSFiddle with the code below. He does not find a match. It returns null.

var re = RegExp('^\d+(?:\.\d{0,1})?$'); var myString = "123"; alert(myString.match(re)); 

I am trying to use the below javascript on an aspx webpage. He does not find a match. I am open to ideas.

 function ValidateData(ControlObj, ColumnType) { var re = new RegExp('^\d+(?:\.\d{0,1})?$'); if (!ControlObj.value.match(re)) { 
+6
source share
2 answers

It is better to use a regex literal instead of a regex object:

 var re = /^\d+(?:\.\d?)?$/; var myString = "123"; alert(myString.match(re)); 

Until you create a dynamic expression dynamically, there is no need to use a RegExp object.

Otherwise, the RegExp object needs double escaping, for example:

 var re = RegExp('^\\d+(?:\\.\\d?)?$'); 

The reason for double escaping is because the RegExp object accepts the string as input, and first requires escaping for the string and a second for the regex engine.

btw \d{0,1} can be replaced by \d?

+8
source

Use double escaped slashes:

 var re = RegExp('^\\d+(?:\\.\\d{0,1})?$'); 

And it should work.

In JavaScript, you can use a literal and constructor. In literal notation (see the anubhava clause) you need to add / ... / and then you don't need to hide slashes. When using a RegExp object (constructor), you should avoid backslashes.

The constructor is good when you need to pass variables to your template. In other cases, a literal entry is preferred.

 var re = /^\d+(?:\.\d?)?$/; 

\d{0,1} matches \d? how ? means 0 or 1, greedy .

See this MDN difference for more details .

Literal notation provides compilation of a regular expression when an expression is evaluated. Use letter notation if the regular expression remains constant. For example, if you use a literal notation to build the regular expression used in the loop, the regular expression will not be recompiled at each iteration.

The regular expression object constructor, for example, the new RegExp ('ab + c'), provides compilation of the runtime expression of the regular expression. Use the constructor function when you know the pattern of the expression will change, or you don't know the pattern and get it from another source, such as user input.

When using the constructor function, normal string escape rules (preceding special characters with \ when included in the string) are necessary.

+3
source

Source: https://habr.com/ru/post/986849/


All Articles