NSRegularExpression escaping parentheses

人盡茶涼 提交于 2019-12-13 18:28:05

问题


I'm using regular expressions to find some values in a string, however, what I'm trying to find looks something like this:

Dealt to SanderDecler [2s 5d]

But I can't seem to find a way to escape these square brackets, I've had the same problem with parentheses earlier. I've tried to escape them like this \( or \[, but that didn't give any matches. So I just replaced that with a dot, and it did match, however, that doesn't seem like the best way to do it, and I can imagine it's better for performance to specify the exact character too...

So my question is, how can I match parantheses and square brackets?

Here's how my code looks like now, this is working, but non-optimal:

    NSString *expression = 
    @"^Dealt to (.{1,12}) .([0-9TJKQA][cdhs]) ([0-9TJKQA][cdhs]).";

    NSRegularExpression *regex = 
    [NSRegularExpression regularExpressionWithPattern:expression
                                              options:NSRegularExpressionAnchorsMatchLines
                                                error:nil];

    for (NSTextCheckingResult *result in [regex matchesInString:history options:NSMatchingReportCompletion range:NSMakeRange(0, history.length)]) 
    {
        NSLog(@"%@", [history substringWithRange:[result rangeAtIndex:0]]);
    }

回答1:


Try this:

@"^Dealt to (.{1,12}) \\[([0-9TJKQA][cdhs]) ([0-9TJKQA][cdhs])\\]"


来源:https://stackoverflow.com/questions/8960528/nsregularexpression-escaping-parentheses

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!