gpt4 book ai didi

ios - 正则表达式捕获 { 字符之前的所有文本 - Objective C

转载 作者:行者123 更新时间:2023-11-29 11:58:47 25 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 colorFromHexString:@"#C41A16"] range:[match range]];
}

我正在尝试设置以下 CSS 代码的样式,使 p 是彩色的,a 是彩色的:

p {
color: blue;
}

a {
color: red;
}

最佳答案

How would I write a regex to capture all text before the { character but on the same line?

使用

pattern = @"(?m)^([^{\r\n]*)\\{";

这只会匹配和捕获从开始到第一个 { 的行的一部分,并且会匹配 { 本身。 [^{\r\n] 否定字符类只匹配{、CR 和LF 以外的字符。

参见 regex demo

要仅匹配 { 之前的文本(不包括 {),您可以使用前瞻:

pattern = @"(?m)^[^{\r\n]*(?=\\{)";
^^^^^^^

参见 another regex demo

最后,您还可以借助惰性 *? 量词和前瞻内的 *(零个或多个空格)来“修剪”匹配项:

pattern = @"(?m)^[^{\r\n]*?(?= *\\{)";

another demo

关于ios - 正则表达式捕获 { 字符之前的所有文本 - Objective C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37955793/

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