Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex accepts * without specifing it in the pattern

Developing a JavaScript regex, we found out some weird behaviour.

For following pattern: [\'-=]

The character * is accepted. (', -, = are also accepted but this is expected.)

We can replace '=' by any character. If we change pattern characters order, it does not work anymore.

Anyone got an idea about this?

like image 245
benjamin Avatar asked Feb 15 '12 13:02

benjamin


People also ask

What is the use of * in regular expression?

*. * , returns strings beginning with any combination and any amount of characters (the first asterisk), and can end with any combination and any amount of characters (the last asterisk). This selects every single string available.

What is the difference between * and in regex?

represents any single character (usually excluding the newline character), while * is a quantifier meaning zero or more of the preceding regex atom (character or group). ? is a quantifier meaning zero or one instances of the preceding atom, or (in regex variants that support it) a modifier that sets the quantifier ...

What does regex 0 * 1 * 0 * 1 * Mean?

Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1.

What does asterisk mean in regex?

The asterisk ( * ): The asterisk is known as a repeater symbol, meaning the preceding character can be found 0 or more times. For example, the regular expression ca*t will match the strings ct, cat, caat, caaat, etc.


1 Answers

The "-" character in the middle of the pattern is what's causing your problem. The "-" character is special inside character groups like that, and it means "all the characters between". Thus, "'-=" means "all characters from "'" through "=". It happens that "*" is in that range.

To fix it, re-order the list of characters so that the "-" is at the end, or else quote it with a backslash.

like image 146
Pointy Avatar answered Nov 15 '22 08:11

Pointy