Java Regex for substring search

I have the line "Class (102) (401)" and "Class (401)". I want to find a regex to find a substring that always returns me the last value of the bracket, in my case it is "(401)"

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

He returns

- (-) - (-)

+3
source share
3 answers

You can use:

Pattern MY_PATTERN = Pattern.compile(".*(\\(\\d+\\))");

Take a look

+2
source

Try the following:

(?<=\()[^\)(]+(?=\)[^\)\(]+$)

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) «$»
-->
+1
source

: .*\\(([^\\(\\)]+)\\)[^\\(\\)]*$

(, [^\\(\\)] ( ), ), ,

+1

All Articles