最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Regex match not returning true or false - Stack Overflow

programmeradmin1浏览0评论

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: .html

Here is my fiddle: /

thanks

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/valamas/8B5zw/

thanks

Share Improve this question asked Sep 27, 2012 at 1:45 ValamasValamas 24.7k25 gold badges110 silver badges181 bronze badges 0
Add a ment  | 

4 Answers 4

Reset to default 4
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./exec-vs-match-vs-test/5

发布评论

评论列表(0)

  1. 暂无评论