0

I am trying to learn regex but can't figure out how the following regex works.

It is used to identify java block comments like /*blah blah*/:

Regex

\/\*\_.\{-}\*\/

I know that

  • \/\* at the beginning is for matching /* and
  • \*\/ at the end is for matching */.

Issue

But I can't interpret \_.\{-}.

What pattern does this expression stand for?

hc_dev
  • 8,389
  • 1
  • 26
  • 38
user3552506
  • 45
  • 1
  • 1
  • 7
  • regex is wrong.. It won't get the comments.. Did you test the regex? – Avinash Raj Jan 05 '16 at 07:51
  • It is a VIM regex. `\_.\{-}` matches any characters incl. a newline lazily (same as `.*?` in most engines). Note that `\_.*` matches any characters including a newline *greedily*. – Wiktor Stribiżew Jan 05 '16 at 07:51
  • @stribizhev: You say this is a VIM regex, but you marked the question as a duplicate of one about PHP/Perl/JavaScript/Python/Ruby/Java/.Net regexes . . . – ruakh Jan 05 '16 at 08:01
  • If you want, re-close with [vim search replace including newline](http://stackoverflow.com/questions/32434640/vim-search-replace-including-newline/32434899#32434899). It is still an off-topic question. [Learning Regular Expressions](http://stackoverflow.com/a/2759417/3832970). Seems like it is time to update the [Reference - What does this regex mean?](http://stackoverflow.com/questions/22937618/reference-what-does-this-regex-mean)!!! :) – Wiktor Stribiżew Jan 05 '16 at 08:02
  • i have tested it and it works – user3552506 Jan 05 '16 at 08:03
  • \* I meant to say *same as `(?s).*?` in most engines*. – Wiktor Stribiżew Jan 05 '16 at 08:20
  • 1
    In general case, you want a parser: imagine that you have a java string: `String s = "abc /* def */ pqr";`, note that `/* def */` is not a comment. Same problem is for `// /* abc */` – Dmitry Bychenko Jun 26 '23 at 09:08
  • Does this answer your question? [vim search replace including newline](https://stackoverflow.com/questions/32434640/vim-search-replace-including-newline) – hc_dev Jul 10 '23 at 16:23

1 Answers1

0

To match comments like /*blah blah*/ you must use a regex like this:

/\/\*\_.\{-}\*\/

because\/ is used to match simple / character, then \* for *, and \_. match everything, finally \{-} is non-greedy operator.

Alan Gómez
  • 211
  • 1
  • 6