简体   繁体   中英

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

Here is my fiddle: 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.

You regex should be var re = new RegExp("\\\\(.*?\\\\)"); , but since there is no variable in your regex, you should just use the regex literal instead.

.match() returns an array of matching groups.

You're thinking of .test() , which returns true or false.

Also, your \\ s are being swallowed by the Javascript string literal.
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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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