Problem when capturing text between two letters
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开发者_如何学C 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?
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.
It looks like you're using greedy matching between the comment delimiters. Try this instead
(/\*)+(.+?)(\*/)
精彩评论