JavaScript正则表达式的麻烦

时间:2011-05-12 06:43:06

标签: javascript regex

我有一个棘手的时间让这个正则表达式工作。我到目前为止的模式是:

var dollarPattern = /^\d{1,}|\s\d/gi;

var matchedResults = new Array();
matchedResults = textValue.match(dollarPattern);

我希望实现的是使用示例字符串“2到2.99(63项)”,我想检查它是以数字开头,还是包含空格后跟数字(在这种情况下) ,两个条件都是真的)。但是,我在Firefox中不断收到“matchedResults为null”错误(尽管它的长度应为2)。

任何想法我做错了什么?感谢...

2 个答案:

答案 0 :(得分:2)

你需要的只是逃避。

// Please note that this works, but @Lekensteyn pointed out that this uses string literals
// Also, this will give you the first match(if exists) only.
alert("2 to 3.99 (63 items)".match("^\\d\|\\s\\d"));

OR

// This one will give you all possible matches
alert("2 to 3.99 (63 items)".match(/^\d|\s\d/g));

答案 1 :(得分:0)

在Chrome,FF4和IE8中正常运行。

当我在正则表达式周围加上引号时,我得到null。

然而,输出我得到它“2,2”。