Java正则表达式:如果右括号是字符串中的最后一个字符,则匹配圆括号中的任意数量的数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20846895/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java Regular Expression: match any number of digits in round brackets if the closing bracket is the last char in the String
提问by Kovács Imre
I need some help to save my day (or my night). I would like to match:
我需要一些帮助来挽救我的一天(或我的夜晚)。我想匹配:
- Any number of digits
- Enclosed by round brackets "()" [The brackets contain nothing else than digits]
- 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!
谢谢!
采纳答案by anubhava
You can try this regex:
你可以试试这个正则表达式:
String regex = "\(\d+\)$";
回答by Sabuj Hassan
This is the required regex for your condition
这是您的条件所需的正则表达式
\(\d+\)$
回答by ajb
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 notpreceded 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)
,因为这是正则表达式中的第一个也是唯一的捕获组。)