简体   繁体   English

OS X在正则表达式中使用文字星号

[英]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). 我正在编写一个程序,使以/*开头并以*/结束的文本使用不同的颜色(C注释的语法突出显示)。 When I try this 当我尝试这个

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

I get unknown escape sequence . 我得到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. \\*是转义序列*在正则表达式,但在C字符串, \\也开始一个转义字符标记,所以你必须逃离一点。

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

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. 例如,转义序列可能是\\t ,它代表一个制表符,或者\\n ,代表换行符。 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. 您的错误是说\\*不是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. 您应该NSLog结果数组包含的内容以查看您得到的匹配项。 If the matches are what you expect, then the problem is not with the regex. 如果匹配符合您的期望,则问题不在于正则表达式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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