Regular expression to select anything between * …. and …. *

Question:

I want to write a regular expression for multiline comments.

My Expression: \*[sS]*?*/

What I expect:

1)

/* 

this is a comment

*/

Not a comment 

/*

new comment

*/
/*
comment 1
comment 3
*/
Not a comment
Not a comment
*/

The output I get:

  1. Example 1
  2. Example 2
Asked By: Tom

||

Answers:

Your RegEx is matching the wrong type of slash. \* is parsed from start to end, so \ is interpreted as the escape sequence for , and that leaves your * character unescaped. To fix this, use /* to start your RegEx, or use /* with a raw string in Python. Like this:

import re


test1 = '''
/*

this is a comment

*/

Not a comment 

/*

new comment

*/
'''

test2 = '''
/*
comment 1
comment 3
*/
Not a comment
Not a comment
*/
'''

# out1 = re.findall(r'/*.*?*/', test1)
out1 = re.findall(r'/*([sS]*?)*/', test1)
print(out1)

out2 = re.findall(r'/*([sS]*?)*/', test2)
print(out2)
Answered By: Michael M.
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.