Ahmet Karakaya
Ahmet Karakaya

Reputation: 10139

Regular Expression with multiple lines search

I have two types of comments as following. I have regular expression \/\*.*\*\/ does not find second type of comments but first one. I think it is because of its having multiple lines?

What modification is required for regular expression to find both types of comments?

First type:

/* Comment type1 */

Second type:

/* 

 * JD-Core Version:    0.7.0.1

 */

Upvotes: 0

Views: 3682

Answers (5)

Avinash Raj
Avinash Raj

Reputation: 174696

Your regex should be the below with sg modifiers,

/\/\*.*?\*\//sg

If you want to capture the text which was present inside the /* */, the go for the below regex,

/\/\*(.*?)\*\//sg

Explanation:

s    #  Dotall
g    #  global
*?   #  Non-greedy match

DEMO

Upvotes: 0

zx81
zx81

Reputation: 41838

Assuming your language does not check if comments are nested, you can go for this:

(?s)/\*.*?\*/

You say you use Notepad++: here is a screenshot of the regex at work.

Notepad++ Regex

Upvotes: 3

Hermios
Hermios

Reputation: 634

I suggest another solution:

\/\*([\S\s]+?)\*\/

This will avoid the dot, who is greedy in resouces.

Upvotes: 6

Bergi
Bergi

Reputation: 664307

The dot . does not always match newlines. You can try to use flags to modify this, or use an explicit character class. Here is a version that does not allow everything but the sequence */ inside the comment:

/\/\*([^\/]|[^*]\/)*\*\//

(demo)

Upvotes: 0

Bohemian
Bohemian

Reputation: 424983

The dot doesn't match newlines, so add the DOTALL flag (s) to your regex:

/\/\*.*?\*\//s

And use a reluctant quantifier for the dot .*? (ie add a question mark) so it will stop at the first closing */

Upvotes: 0

Related Questions