Regular expression – problems when capturing text between two letters

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

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

This method is good when this only needs to happen once, for example, when the entire string is like this.

< pre>/* hello */
it only needs to capture once

But if it needs to capture it more than once, it will capture the things in between, for example:

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

why ?

because you told it. By default, regexps are greedy, which means they will match The longest thing.

In Perl regexp, you can override this behavior by

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

‘? ‘Tell” to match the shortest string, not the longest string.

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

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

When this only needs to happen once, such as the entire string When that’s it, this method is good

/* hello */
it only needs to capture once

But if you need it more than once Capture it, it will capture something in between, for example:

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

Why is this?

Because you told it. By default, regexp Are greedy, which means they will match the longest thing.

In Perl regexp, you can override this behavior by

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

‘?’ tells “match the shortest string, not the longest string.

Leave a Comment

Your email address will not be published.