Home > Enterprise >  Regex Patternst Match Wrong Strings
Regex Patternst Match Wrong Strings

Time:03-04

There is my regex

\[a:section(.*)\](.*)\[\/a:section\]

https://regex101.com/r/wtN6Rk/1

I wanna detect like this

Group1 : asasasas   
Group2 : [a:widget type=blog][a:widget type=blog][a:widget type=blog]  

But my regex code match wrong, How can I fix it?

Edit : If I don't use "[" string in group2, It works what I want.

CodePudding user response:

.* is greedy. It will matches any character, as many as possible.

Instead, you should better use .*?, which is the lazy alternative (matches any character as few as possible).

You can test the demo here.


Another option indicated by @Casimir et Hippolyte may be to replace the dot with a character class that excludes the closing square bracket, like that [^]]. It's also faster (54 steps instead of 74).

You can test it here.

  • Related