NSRegularExpression 转义括号
我正在使用正则表达式来查找字符串中的一些值,但是,我试图找到的内容看起来像这样:
Dealt to SanderDecler [2s 5d]
但我似乎找不到一种方法来转义这些方括号,我也有同样的情况之前的括号问题。我试图像这样 \( 或 \[ 一样转义它们,但这没有给出任何匹配。所以我只是用点替换它,它确实匹配,但是,这似乎不是最好的方法这样做,我可以想象指定确切的字符对性能也更好...
所以我的问题是,如何匹配括号和方括号?
这是我的代码现在的样子,这是有效的,但不是最佳的:
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]]);
}
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]]);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
试试这个:
Try this: