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

时间:2021-12-23 21:45:04

I need some help to save my day (or my night). I would like to match:

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

  1. Any number of digits
  2. 任意数量的数字
  3. Enclosed by round brackets "()" [The brackets contain nothing else than digits]
  4. 用圆括号括起来“()”[括号中只包含数字]
  5. If the closing bracket ")" is the last character in the String.
  6. 如果结束括号“)”是字符串中的最后一个字符。

Here's the code I have come up with:

这是我提出的代码:

// 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();
            }

Please help me out with the magic expression I have only managed to match any number of digits, but not if they are enclosed in brackets and are at the end of the line...

请帮我解决我只能设置匹配任意数字的神奇表达式,但如果它们括在括号中并且位于行尾,请不要帮助我...

Thanks!

谢谢!

3 个解决方案

#1


3  

You can try this regex:

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

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

#2


2  

This is the required regex for your condition

这是您的病情所需的正则表达式

\\(\\d+\\)$

#3


2  

If you need to extract just the digits, you can use this regex:

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

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

and get the value of matcher.group(1). (Explanation: The ( and ) characters preceded by backslashes match the round brackets literally; the ( and ) characters not preceded by backslashes tell the matcher that the part inside, i.e. just the digits, form a capture group, and the part matching the group can be obtained by matcher.group(1), since this is the first, and only, capture group in the regex.)

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

#1


3  

You can try this regex:

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

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

#2


2  

This is the required regex for your condition

这是您的病情所需的正则表达式

\\(\\d+\\)$

#3


2  

If you need to extract just the digits, you can use this regex:

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

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

and get the value of matcher.group(1). (Explanation: The ( and ) characters preceded by backslashes match the round brackets literally; the ( and ) characters not preceded by backslashes tell the matcher that the part inside, i.e. just the digits, form a capture group, and the part matching the group can be obtained by matcher.group(1), since this is the first, and only, capture group in the regex.)

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