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
Add a ment  | 

4 Answers 4

Reset to default 8

The * 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