Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem when capturing text between two letters

Tags:

regex

perl

I am using the following regular expression to get text between /* and */:

(/\*)+(.+)(\*/)

this works fine when this only needs to happen once e.g the whole string is just

/* hello */
it only needs to capture once

but if there is more than one time where it needs to be captured it grabs what ever is in between for example:

/* hello */
it only needs to capture more than once [THIS ALSO GET'S HIGHLIGHTED]
/* second time */

Why does this happen?

like image 646
Joshua Avatar asked Apr 25 '26 07:04

Joshua


1 Answers

Because you're telling it to. By default, regexp's are greedy, meaning that they will match the longest thing they can.

In Perl regexp, you can override that behaviour by

(/\*)+(.+?)(\*/)

The '?' tells the '+' to match the shortest string it can, instead of the longest.

like image 192
Colin Fine Avatar answered Apr 26 '26 22:04

Colin Fine



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!