gpt4 book ai didi

ios - 为 $ - NSString 中的文本着色

转载 作者:行者123 更新时间:2023-11-29 11:58:53 26 4
gpt4 key购买 nike

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com