Question

I have hard time trying to decipher this expression:

[[NSRegularExpression regularExpressionWithPattern:@"^([^:]+?):([^:]+?):([^:]+?):(.*)$" options:NSRegularExpressionCaseInsensitive error:nil]

Any of you can help me to figure out what exactly is doing?

I'll really appreciate your help.

Was it helpful?

Solution

This expression takes a four-part string separated with three colons, for example

quick:brown:fox:jumps

The only requirement to that string is that three colons must be there, that the items between the colons (or between the colon and the beginning/the end of the string) had at least one non-colon character, and that the content occupied the entire string.

The expression creates four capturing groups - one for each of the colon-separated elements of the string.

Since the non-colon character class [^:]+? is always followed by a colon, the reluctant quantifier can be removed:

^([^:]+):([^:]+):([^:]+):(.*)$

A way to accomplish the same thing without a regex would be using componentsSeparatedByString:, and checking that you get exactly four components back:

NSArray *parts = [str componentsSeparatedByString:@":"];
if (parts.length == 4) {
    ... // We've got a good string
}

OTHER TIPS

The leading ^ means "start of line". The trailing $ means end of line. So the whole line must match what is in between.

The expression [^:] means "any character except the colon". Followed by a +? it means "one or more of those but match as few as possible".

The .* means "zero or more of any character".

The colons outside the parens mean actual colons must be in string at that point.

The parens are used for grouping.

In the end, you string must be in the form:

0 or more characters other than a colon, then a colon, 0 or more characters other than a colon, then a colon, 0 or more characters other than a colon, then a colon, then 0 or more characters of any kind.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top