我有以下字符串“Class(102)(401)”和“Class(401)”我想找到正则表达式来查找子字符串总是返回我的最后一个括号值,在我的情况下它是'(401)'
以下是我的代码
Pattern MY_PATTERN = Pattern.compile(".*(\\(\\d+\\))");
Matcher mat = MY_PATTERN.matcher("Class (102) (401)");
while (mat.find()){
System.out.println(mat.group());
}
它正在返回
- ( - ) - ( - )
答案 0 :(得分:2)
答案 1 :(得分:1)
试试这个:
(?<=\()[^\)(]+(?=\)[^\)\(]+$)
<强>解释强>
<!--
(?<=\()[^\)(]+(?=\)[^\)\(]+$)
Options: ^ and $ match at line breaks; free-spacing
Assert that the regex below can be matched, with the match ending at this position (positive lookbehind) «(?<=\()»
Match the character “(” literally «\(»
Match a single character NOT present in the list below «[^\)(]+»
Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
A ) character «\)»
The character “(” «(»
Assert that the regex below can be matched, starting at this position (positive lookahead) «(?=\)[^\)\(]+$)»
Match the character “)” literally «\)»
Match a single character NOT present in the list below «[^\)\(]+»
Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
A ) character «\)»
A ( character «\(»
Assert position at the end of a line (at the end of the string or before a line break character) «$»
-->
答案 2 :(得分:1)
表达式如何:.*\\(([^\\(\\)]+)\\)[^\\(\\)]*$
它找到一个(
后面跟着非括号[^\\(\\)]
(你想要的字符串)后跟一个)
,之后只允许非括号,所以它必须是最后一个