NSRegularExpression 转义括号

发布于 2024-12-28 05:45:58 字数 907 浏览 1 评论 0原文

我正在使用正则表达式来查找字符串中的一些值,但是,我试图找到的内容看起来像这样:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

别理我 2025-01-04 05:45:58

试试这个:

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

Try this:

@"^Dealt to (.{1,12}) \\[([0-9TJKQA][cdhs]) ([0-9TJKQA][cdhs])\\]"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文