开发者

regex match a string left of a c++ comment

I'm looking for a pattern to extract a string left of a c++ comment and the comment itself. The problem is, the left side can contain a single slash as well.

Example:

"abc/def//comment"

As a result, I would like to have 2 groups which contains the开发者_开发百科 left side of the comment and the comment itself:

  1. abc/def
  2. //comment

Any suggestions?


Assuming you're processing the file line-by-line, this regex will do what you want:

((?:(?!//).)*)(//.*)

or simply:

(.*?)(//.*)

I.e., group 1 contains abc/def and group 2 contains //comment.

Be aware that when this fails with string literals and multi-line comments (to name just two pit-falls):

"a string with // in it"

/*
// not a comment!
*/


echo "abc/def//comment" | sed -r 's|(.*)//(.*)|\1 //\2|'
abc/def //comment

What about multiple pairs of slashes? Comments inside Strings are ok?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜