pattern = @"(\\$.*?\\$)";
regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:&error];
matches = [regex matchesInString:self options:0 range: searchedRange];
for (NSTextCheckingResult* match in matches) {
[string addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:[match range]];
}
我正在使用上面的代码为两个美元符号之间的文本着色。因此,以下字符串中的 hello world 文本将变为蓝色,并移除美元符号:
@"This won't be blue. $hello world$. This won't be blue";
但是,现在我希望单个美元符号不要被涂成蓝色。我只希望模式在第一个美元符号后跟 a-zA-Z0-9 中的字符时匹配,同样,第二个美元符号前面应该有 a-zA-Z0-9 中的字符。我该怎么做?
最佳答案
将捕获组移动到第一个 $
之后一点在最后一个 $
之前,并使用 matchAtIndex:1
仅获取第 1 组值:
pattern = @"\\$([A-Za-z0-9].*?)(?<=[A-Za-z0-9])\\$";
^ ^^^^^^^^^^ ^^^^^^^^^^^^^^^^
和
[string addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:[match matchAtIndex:1]];
图案细节:
-
\\$
- 文字$
-
([A-Za-z0-9].*?)
- 一个字母或数字后跟 0+ 任何字符,但换行符尽可能少,直到第一个 -
(?<=[A-Za-z0-9])\\$
-$
以字母或数字开头
如果你只需要确保第一个$
之后出现一个数字或字母, 使用
pattern = @"\\$\\b(?!_)(.*?)\\$";
哪里第一个$
后面可以跟字母或数字,但不能跟_
.
关于ios - 为 $ - NSString 中的文本着色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37903685/