Apollo Apollo - 5 months ago 8
Objective-C Question

Regex to capture all text before { character - Objective C

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

I tried something like the following:

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]];
}


I'm trying to style the following CSS code such that p is colored and a is colored:

p {
color: blue;
}

a {
color: red;
}

Answer

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

Use

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

This will only match and capture a part of the line from the start till the first { and will match the { itself. The [^{\r\n] negated character class only matches a character other than {, CR and LF.

See the regex demo

To match the text before the { only (excluding {) you may use a lookahead:

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

See another regex demo

And finally, you may also "trim" the match with the help of a lazy *? quantifier and the * (zero or more spaces) inside the lookahead:

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

Yet another demo

Comments