简体   繁体   中英

What's the correct IOS regex

I basically am expecting a string in the form of \\w+:\\w+ or \\w+:\\w+:\\w+. I made a regex that can match each of those cases individually ...

NSRegularExpression *individualConstraintRegex = [NSRegularExpression regularExpressionWithPattern:@"^(\\w+?):(\\w+?)$" options:0 error:NULL];

and

NSRegularExpression *individualConstraintRegex = [NSRegularExpression regularExpressionWithPattern:@"(^\\w+?):(\\w+?):(\\w+?)$" options:0 error:NULL];

However I tried to use the '|' symbol to achieve an OR effect but it doesnt work.

NSRegularExpression *individualConstraintRegex = [NSRegularExpression regularExpressionWithPattern:@"^(\\w+?):(\\w+?):(\\w+?)$|^(\\w+?):(\\w+?)$" options:0 error:NULL];

I'm sure the solution is simple, any ideas?

Your expression puts an OR in between of wrong subexpressions, ie $|^ is an "OR" between ^ and $ , making any match impossible.

Use parentheses for proper grouping:

NSRegularExpression *individualConstraintRegex = [NSRegularExpression
    regularExpressionWithPattern:@"^(?:(\\w+?):(\\w+?):(\\w+?))|(?:(\\w+?):(\\w+?))$"
                         options:0
                           error:NULL
];

(?:...) are non-capturing parentheses. They group parts of your expression without creating a new capturing group . I also moved the common anchors ^ and $ outside the brackets.

Note that since : is not a word character, you can drop the reluctant qualifier ? , and use + instead. Another alternative would be making the third :\\\\w+ part optional, like this:

NSRegularExpression *individualConstraintRegex = [NSRegularExpression
    regularExpressionWithPattern:@"^(\\w+)[:](\\w+)(?:[:](\\w+))?$"
                         options:0
                           error:NULL
];

I added [:] around columns for readability. They are not necessary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM