admin管理员组文章数量:1302379
I have a string.
var string="ghtykj";
var pattern = "t*y";
When I give new RegExp(pattern).test(string), it returns true(as expected).
var pattern = "t*g";
But this pattern also returns true.
I was expecting this pattern to return false, since t*g means t followed by zero or more number of characters ,followed by g.
If this is indeed the expected behavior , could any one correct me where i am doing wrong?
I have a string.
var string="ghtykj";
var pattern = "t*y";
When I give new RegExp(pattern).test(string), it returns true(as expected).
var pattern = "t*g";
But this pattern also returns true.
I was expecting this pattern to return false, since t*g means t followed by zero or more number of characters ,followed by g.
If this is indeed the expected behavior , could any one correct me where i am doing wrong?
Share edited May 16, 2015 at 15:47 user4227915 asked May 16, 2015 at 15:00 RenjithRenjith 3,27421 silver badges39 bronze badges 1- You seem to confuse regular expressions with glob: en.wikipedia/wiki/Glob_%28programming%29 – Felix Kling Commented May 16, 2015 at 15:09
4 Answers
Reset to default 8The *
isn't a wildcard character in a regular expression, is a quantifier. It has the same meaning as the quantifier {0,}
, i.e. specifying that the expression before it (in this case the character t
) can occur zero or more times.
The pattern t*g
doesn't mean t followed by zero or more number of characters, followed by g. It means zero or more of the character t, followed by one g.
The pattern t*g
would match for example tg
or tttttg
, but also just g
. So, it matches the g
character at the beginning of the string.
To get a pattern that matches t followed by zero or more number of characters, followed by g you would use t.*g
(or t[\w\W]*g
to handle line breaks in the string).
since t*g means t followed by zero or more number of characters ,followed by g.
This is incorrect. This means 0 or more t
, so t
is optional.
You may be thinking instead of Globbing in terminal shells where the *
operator would work as you expected. However Globbing *
has different behaviour from RegEx *
.
You want
var pattern = "t.*g";
This means, .
is optional (0 or more instances), but there must be a t
.
In Regular Expressions, .
matches almost any character.
You should test your regex here: regex101, it will translate your regex into english so its easier to understand.
var pattern = "t.*g";
should be right. t*
means 0 or any number of t, which is true
本文标签: jqueryJavascript RegExp 39 * 39 not working as expectedStack Overflow
版权声明:本文标题:jquery - Javascript RegExp ' * ' not working as expected - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741696490a2393033.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论