I'm trying to build regex that removes *
and =
or any combination of them from the end of the string, so I tried "[*=]$"
, but it was lazy, for example, if I have the string this is a dog =*
, then it will remove *
and keep =
, then I tried the regex [*=]+$
, and it did the job, But I can't understand how the regex engine would work with the last regex, or in another word, how this regex become greedy.
Asked
Active
Viewed 62 times
-3

hbak
- 1,333
- 3
- 10
- 22
-
NOte that `+` repeats the previous token one or more times. So `[*=]+` matches one or more `*` or `=` symbols exists at the last. – Avinash Raj Dec 15 '15 at 06:48
-
use https://regex101.com/ if you want to try regex, or any other regex tester – Slasko Dec 15 '15 at 06:50
1 Answers
0
Note that +
repeats the previous token one or more times. So [*=]+
matches one or more *
or =
symbols exists at the last.
What happens in the background is, at first [*=]
matches all the *
or =
symbols (matching continuous characters). Once after regex engine saw the +
which exists next to the char class, then it starts to match the following *
or =
symbols. And finally once it saw the end of the line anchor $
, all the matches other than the one exists at the last will get discarded by the regex engine. Now, you left with the last match (match exists at the end of a line).

Avinash Raj
- 172,303
- 28
- 230
- 274