Reputation: 58083
I have following string "Class (102) (401)" and "Class (401)" i want to find regex to find substring which always return me last bracket value in my case it is '(401) '
Following is my code
Pattern MY_PATTERN = Pattern.compile(".*(\\(\\d+\\))");
Matcher mat = MY_PATTERN.matcher("Class (102) (401)");
while (mat.find()){
System.out.println(mat.group());
}
It is returning
--( --) --( --)
Upvotes: 3
Views: 774
Reputation: 3289
how about the expression: .*\\(([^\\(\\)]+)\\)[^\\(\\)]*$
it finds a (
followed by non-brackets [^\\(\\)]
(your desired string) followed by a )
and after that are only non-brackets allowed, so it must be the last
Upvotes: 1
Reputation: 11182
Try this:
(?<=\()[^\)(]+(?=\)[^\)\(]+$)
Explanation:
<!--
(?<=\()[^\)(]+(?=\)[^\)\(]+$)
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) «$»
-->
Upvotes: 1