3

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

--( --) --( --)

1
  • 2
    How about getting the index of the last ( and ) and getting the substring between the two? Commented May 3, 2012 at 8:23

3 Answers 3

2

You can use:

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

See it

Sign up to request clarification or add additional context in comments.

4 Comments

i tried and it returns "Class (102) (401)" i want only last value which is in last bracket '401'
@Faisalkhan: You need to use group(1). See the working link.
one more small help if i want 401 instead (401) then what will be the change ?
@Faisalkhan: Use the pattern: ".*\\((\\d+)\\)"
1

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.