Regexp in iOS to find comments

Posted by SteveDolphin23 on Stack Overflow See other posts from Stack Overflow or by SteveDolphin23
Published on 2013-11-02T09:50:32Z Indexed on 2013/11/02 9:53 UTC
Read the original article Hit count: 158

Filed under:
|

I am trying to find and process 'java-style' comments within a string in objective-C.

I have a few regex snippets which almost work but I am stuck on one hurdle: different options seem to make the different styles work.

For example, I am using this to match:

NSArray* matches = [[NSRegularExpression regularExpressionWithPattern:expression options:NSRegularExpressionAnchorsMatchLines error:nil] matchesInString:string options:0 range:searchRange];

The options here allow me successfully find and process single line comments (//) but not multiline (/* */), if I change the option to NSRegularExpressionDotMatchesLineSeparators then I can make multiline work fine but I can't find the 'end' of a single line comment.

I suppose really I need dot-matches-line-separators but I need a better way of finding the end of a single line comment?

The regexp I have so far are:

@"/\\*.*?\\*/"
@"//.*$"

it's clear to see if dot matches a line separator then the second one (single line) never 'finishes' but how do I fix this? I found some suggestions for single line that were more like:

@"(\/\/[^"\n\r]*(?:"[^"\n\r]*"[^"\n\r]*)*[\r\n])"

But that doesn't' seem to work at all!

Thanks in advance for any pointers.

© Stack Overflow or respective owner

Related posts about objective-c

Related posts about regex