Java正则表达式:如果右括号是字符串中的最后一个字符,则匹配圆括号中的任意数量的数字

Kov*_*mre 4 java regex brackets digits

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

  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();
            }
Run Code Online (Sandbox Code Playgroud)

请帮我解决我只能匹配任意数量的数字的魔术表达式,但如果它们用括号括起来并且位于行尾,则不能...

谢谢!

anu*_*ava 5

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

String regex = "\\(\\d+\\)$";
Run Code Online (Sandbox Code Playgroud)

  • 如果你不想在你的结果中有括号,你可以使用 `"\\((\\d+)\\)$";` 和 `matcher.group(1);` 或者你可以使用环视机制像`"(?<=\\()\\d+(?=\\)$)`。 (2认同)