简体   繁体   中英

OS X Using literal asterisk in regular expression

I'm writing a program to make text that begins with /* and ends with */ a different color (syntax highlighting for a C comment). When I try this

@"/\*.*\*/";

I get unknown escape sequence . So I figured that to get a literal asterisk I had to use this

@"/[*].*[*]/";

and I get no errors, but when I use this code

commentPattern = @"/[*].*[*]/";
reg = [NSRegularExpression regularExpressionWithPattern:commentPattern options:kNilOptions error:nil];
results = [reg matchesInString:self.string options:kNilOptions range:NSMakeRange(0, [self.string length])];
for (NSTextCheckingResult *result in results)
{
    [self setTextColor:[NSColor colorWithCalibratedRed:0.0 green:0.7 blue:0.0 alpha:1.0] range:result.range];
}

the text color of the comments doesn't change, but I don't see anything wrong with my regular expression. Can someone tell me why this wont work? I don't think it's a problem with the way I get the results or change their color, because I use the same method for other regular expressions.

You want to use this: "\\\\*" .

\\* is the escape sequence for * in regular expressions, but in C strings, \\ also begins an escaped character token, so you have to escape that as well.

 @"/\\*.*\\*/"; 

I get unknown escape sequence.

A string first converts escape sequences in the string, then the result is handed over to the regex engine. For instance, an escape sequence might be \\t , which represents a tab, or \\n which represents a newline. The string first converts an escape sequence to a special code. Your error is saying that \\* is not a legal escape sequence for an NSString.

The regex engine needs to see a literal back slash followed by a *. To get a literal back slash in a string you need to write \\\\ . However, for readability I prefer using a character class like you did with your second attempt.

You should NSLog what the results array contains to see what matches you are getting. If the matches are what you expect, then the problem is not with the regex.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM