常规的前pression不使用JavaScript工作 [英] regular expression does not work with javascript
问题描述
我有一个正规的前pression,当我与.NET发动机测试它regexplib.com工作。它没有找到使用JavaScript匹配。我也曾尝试的jsfiddle与低于code。它没有找到匹配。它返回null。
VAR重新=正则表达式('^ \\ D +(?:\\?\\ D {0,1})$');
VAR的myString =123;
警报(myString.match(重));
我尝试使用下面的JavaScript在一个aspx页面。它不会找到任何匹配。我打开思路。
函数是validateData(ControlObj,ColumnType){
VAR重=新的RegExp('?^ \\ D +(:\\ \\ D {0,1})$?');如果(!ControlObj.value.match(重)){
更好地使用正则表达式的文本,而不是正则表达式对象:
VAR重= /^\\d+(?:\\.\\d?)?$/;
VAR的myString =123;
警报(myString.match(重));
除非,直到你建立一个正规的前pression动态也没有必要使用正则表达式
对象。
否则正则表达式
对象需要双转义,如:
VAR重新=正则表达式('^ \\\\ D +(:\\\\ D)$?。?');
原因双转义是正则表达式
对象接受一个字符串作为输入和逃避首先需要字符串,第二个为正则表达式引擎。
BTW \\ D {0,1}
可以通过 \\ D来代替?
I have a regular expression that works on regexplib.com when I test it with the .NET engine. It does not find a match with JavaScript. I have also tried JSFiddle with the below code. It 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 in an aspx web page. It does not find any matches. I am open to ideas.
function ValidateData(ControlObj, ColumnType) {
var re = new RegExp('^\d+(?:\.\d{0,1})?$');
if (!ControlObj.value.match(re)) {
Better use regex literal instead of regex object:
var re = /^\d+(?:\.\d?)?$/;
var myString = "123";
alert(myString.match(re));
Unless until you're building a regular expression dynamically there is no need to use RegExp
object.
Otherwise RegExp
object needs double escaping like:
var re = RegExp('^\\d+(?:\\.\\d?)?$');
Reason for double escaping is that RegExp
object takes a string as input and escaping is needed first for string and second for the regex engine.
btw \d{0,1}
can be replaced by \d?
这篇关于常规的前pression不使用JavaScript工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!