Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
794 views
in Technique[技术] by (71.8m points)

regex - Python 3 regular expression to find multiline comment

I'm trying to find comment blocks in PHP source code using regular expressions in Python 3. The PHP comments are in this format:

/**
 * This is a very short block comment
 */

Now I came up with the following regular expression:

'/**[.]+?*/'

I figure that -in combination with the DOTALL flag- should do it, but no. It doesn't find anything. Strange thing is that when I remove the trailing slash, like this:

'/**[.]+?*'

then it finds the following string:

/**
*

I have no idea why the regex can't find an asterisk followed by a slash... I checked the file that I'm searching to double check I didn't have a typo in the comment (I didn't). Also a slash is no special character in regex, so I wouldn't have to escape it. (I tried, but it didn't help.)

Can anyone tell me what's wrong with my regex? :)

By the way, I also came across this! thread where someone tried to do the same in Java. The final winning answer finished his regular expression the same way I do now, so I'm clueless :( Could this be a bug in Python regex or am I completely missing something?

Any help is much appreciated! :D

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use the re.DOTALL flag to make the . character match newlines:

re.compile(r'/**.+?*/', re.DOTALL)

(As a side note, PHP block comments can start with /*, not just /**.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...