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:
- abc/def
- //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?
精彩评论