问题
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