admin管理员组文章数量:1435208
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 04 Answers
Reset to default 4var 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
本文标签: javascriptRegex match not returning true or falseStack Overflow
版权声明:本文标题:javascript - Regex match not returning true or false - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745632367a2667350.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论