Reputation: 3274
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?
Upvotes: 5
Views: 388
Reputation: 59601
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.
Upvotes: 6
Reputation: 700302
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).
Upvotes: 8
Reputation: 232
You should test your regex here: regex101, it will translate your regex into english so its easier to understand.
Upvotes: 3
Reputation: 35
var pattern = "t.*g";
should be right. t*
means 0 or any number of t, which is true
Upvotes: 1