简体   繁体   English

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

[英]Java Regular Expression: match any number of digits in round brackets if the closing bracket is the last char in the String

I need some help to save my day (or my night). 我需要一些帮助来保存我的一天(或我的夜晚)。 I would like to match: 我想匹配:

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

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! 谢谢!

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

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

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

\\(\\d+\\)$

If you need to extract just the digits, you can use this regex: 如果你只需要提取数字,你可以使用这个正则表达式:

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

and get the value of matcher.group(1) . 并获取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, ie 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)获得,因为这是正则表达式中第一个也是唯一的捕获组。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM