Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript RegExp ' * ' not working as expected

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?

like image 943
Renjith Avatar asked May 16 '15 15:05

Renjith


People also ask

What is g flag in regex in js?

The g flag indicates that the regular expression should be tested against all possible matches in a string.

What is g modifier in regex?

The "g" modifier specifies a global match. A global match finds all matches (compared to only the first).

What is global flag?

The Global Flags (gflags.exe) utility provides a simple method of setting certain keys within the system registry, adjusting the kernel settings of the running system, and altering the settings for image files. You can set these keys by using a graphical or command-line interface.

What is RegExp test in JavaScript?

The RegExp test() Method in JavaScript is used to test for match in a string. If there is a match this method returns true else it returns false. Where str is the string to be searched. This is required field.


1 Answers

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).

like image 168
Guffa Avatar answered Sep 23 '22 19:09

Guffa