I am not very good at regular expressions, tell me what I'm doing wrong.

Task: It is required to delete all text that starts with /* and ends with */ .

My version: /\*(.|\n|\r)*\*/
If not difficult, explain that I do not understand correctly.

  • /\* - line starts with /*
  • (.|\n|\r)* - any character
  • \*/ - until you meet */
  • one
    * is a special character, denotes 0 or more repetitions of a character. means /* means 0 or more skews, i.e. reacts essentially to anything. put in front of * backslash - Mike
  • I understand, I did not write correctly simply. I mean (. | \ N | \ r) * - like any character, any number of times. Those. in Russian, the whole expression is like: Everything that begins with / * (/ *) then anything can go (. | \ n | \ r) * until it meets * / (* /). Here I mean that I do not understand correctly? - Anton Popov
  • Well, then you basically have everything right, although as suggested in the answer you can use the 's' flag on the expression and then the dot will denote any characters including carriage translations - Mike
  • @Mike, only works if you put a "?" Those. as I understand after / * any character any number of times, * repeating 0 or 1 time (?) until it is * /. I don't quite understand why I need the "?" - Anton Popov

1 answer 1

PHP:

 $text = preg_replace( '#/\*.*?\*/#s', '', $text ); 

Perl:

 $text =~ s#/\*.*?\*/##sg; 

I don't quite understand why I need the "?"

See “Greedy and Lazy Quantifiers,” for example, or what else can be found in any regexp guide on the “greed” of regular expressions, these are the basics of the basics.

In short, with this option: s#/\*.*\*/##sg will capture and delete the entire line until the last */ found, and this:

 "aaa /* bbb\n */ /**/ ccc\nddd /* eee\n */ fff" 

will turn into:

 "aaa fff" 

The “lazy” variant will search until the first match, and the same line will turn into:

 "aaa ccc\nddd fff" 
  • Those. as I understand after / * any character any number of times, * repeating 0 or 1 time (?) until it is * /. I don't quite understand why I need the "?" - Anton Popov
  • @AntonPopov, see addition to the answer. - PinkTux