简体   繁体   English

正则表达式匹配不返回true或false

[英]Regex match not returning true or false

I am trying to match when there is a value with parenthesise. 我试图匹配带有括号的值。

var onsuccess = "aaa;bbb(ccc)";
onsuccess.split(';').forEach(function (success) {
                var re = new RegExp("\(.*?\)");
                document.write(success + ": " + success.match(re) + "<br>");
        });​

Output is 输出是

aaa: ,
bbb(ccc): ,

Expected is 预期是

aaa: false
bbb(ccc): true

Where am I going wrong? 我要去哪里错了? I have been using this page as an example: http://www.regular-expressions.info/javascriptexample.html 我一直以该页面为例: http : //www.regular-expressions.info/javascriptexample.html

Here is my fiddle: http://jsfiddle.net/valamas/8B5zw/ 这是我的小提琴: http : //jsfiddle.net/valamas/8B5zw/

thanks 谢谢

var onsuccess = "aaa;bbb(ccc)";
onsuccess.split(';').forEach(function (success) {
   var re = /\(.*?\)/;
   document.write(success + ": " + re.test(success) + "<br>");
});

The working demo. 工作演示。

Note: if you using new RegExp(...) , you need to escape your backslash. 注意:如果使用new RegExp(...) ,则需要转义反斜杠。

You regex should be var re = new RegExp("\\\\(.*?\\\\)"); 您的正则表达式应为var re = new RegExp("\\\\(.*?\\\\)"); , but since there is no variable in your regex, you should just use the regex literal instead. ,但是由于您的正则表达式中没有变量,因此您应该只使用regex文字。

.match() returns an array of matching groups. .match()返回匹配组的数组。

You're thinking of .test() , which returns true or false. 您正在考虑.test() ,它返回true或false。

Also, your \\ s are being swallowed by the Javascript string literal. 另外,您的\\会被Javascript字符串文字所吞噬。
You should use a regex literal instead. 您应该改用正则表达式文字。

This was missing a group to match, and a cast to boolean: 这缺少要匹配的组,并且缺少布尔值:

var onsuccess = "aaa;bbb(ccc)";
onsuccess.split(';').forEach(function (success) {
                //var re = new RegExp("(\(.*?\))");
                var re = /.*(\(.*?\)).*/;
                document.write(success + ": " + !!success.match(re) + "<br>");
        });​

Use .test instead of casting 使用.test代替强制转换

var onsuccess = "aaa;bbb(ccc)";
var rxParens = /.*(\(.*?\)).*/;

onsuccess.split(";").forEach(function(success) {
    document.write(success + ': ' + rxParens.test(success) + '<br>' );
});

aaa: false
bbb(ccc): true

Just as a side note, .test performs many times faster than .match http://jsperf.com/exec-vs-match-vs-test/5 顺便提一句,.test的执行速度比.match http://jsperf.com/exec-vs-match-vs-test/5快许多倍

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM