Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex for /* ... */

Tags:

c#

regex

I wanted to replace all occurrences of "/* anytext here */" with a blank space (where anytext here could be different types of texts.) What I'm trying to do is replace all comments with blanks.

I created a regex:

Regex regex = new Regex(@"/\*.*\*/");

...but it does not consider the presence of multiple /* ... */ patterns. For example, this string:

"she /*sells*/ sea shells /*by the*/ sea shore" 

...becomes:

"she   sea shore" 

...whereas what I want is:

"she   sea shells   sea shore"

Can someone help with the correct regex?

like image 566
user1582957 Avatar asked Mar 04 '26 06:03

user1582957


1 Answers

Use a lazy quantifier (.*?) instead of a greedy one (.*). By the way, your literal * characters need to be escaped with \*:

Regex regex = new Regex(@"/\*.*?\*/");

A lazy quantifier tries to match as little as possible (= to the first */), whereas a greedy quantifier matches as much as possible (= to the last */). More details can be found at the following MSDN page:

  • Regular Expressions: Greedy and Lazy Quantifiers
like image 149
Heinzi Avatar answered Mar 06 '26 19:03

Heinzi



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!