【问题标题】:Java Regular Expression: match any number of digits in round brackets if the closing bracket is the last char in the StringJava 正则表达式:如果右括号是字符串中的最后一个字符,则匹配圆括号中的任意数量的数字
【发布时间】:2013-12-30 20:22:07
【问题描述】:

我需要一些帮助来挽救我的一天(或我的夜晚)。我想匹配:

  1. 任意位数
  2. 用圆括号“()”括起来[括号中只包含数字]
  3. 如果右括号“)”是字符串中的最后一个字符。

这是我想出的代码:

// this how the text looks, the part I want to match are the digits in the brackets at the end of it
    String text = "Some text 45 Some text, text and text (1234)";  
    String regex = "[no idea how to express this.....]"; // this is where the regex should be
            Pattern regPat = Pattern.compile(regex);
            Matcher matcher = regPat.matcher(text);

            String matchedText = "";

            if (matcher.find()) {
                matchedText = matcher.group();
            }

请帮我解决一下我只能匹配任意数量的数字的魔术表达式,但如果它们被括在括号中并且位于行尾...

谢谢!

【问题讨论】:

    标签: java regex brackets digits


    【解决方案1】:

    你可以试试这个正则表达式:

    String regex = "\\(\\d+\\)$";
    

    【讨论】:

    • 结果仍然有括号,但这已经不是问题了。非常感谢!
    • 如果您不想在结果中包含括号,您可以使用"\\((\\d+)\\)$";matcher.group(1);,或者您可以使用"(?<=\\()\\d+(?=\\)$) 等环视机制。
    • 如果您只想在一个组中捕获数字,那么您可以使用String regex = "\\((\\d+)\\)$";,然后使用matcher.group(1) 仅提取数字。或者 @Pshemo 评论的其他环视
    • 谢谢大家。我将接受阿努巴瓦的回答,首先做出回应。
    【解决方案2】:

    如果你只需要提取数字,你可以使用这个正则表达式:

    String regex = "\\((\\d+)\\)$";
    

    并获取matcher.group(1) 的值。 (说明:反斜杠前面的() 字符在字面上匹配圆括号;() 字符前面的 反斜杠告诉匹配器内部的部分,即只有数字,形成一个捕获组,与组匹配的部分可以通过matcher.group(1)获得,因为这是第一个也是唯一一个捕获正则表达式中的组。)

    【讨论】:

    • 这里的解释很有帮助。
    【解决方案3】:

    这是您的条件所需的正则表达式

    \\(\\d+\\)$
    

    【讨论】:

    • 感谢您的解决方案。
    猜你喜欢
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-15
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多