4

I need some help to save my day (or my night). I would like to match:

  1. Any number of digits
  2. Enclosed by round brackets "()" [The brackets contain nothing else than digits]
  3. 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!

Kovács Imre
  • 715
  • 2
  • 7
  • 17

3 Answers3

6

You can try this regex:

String regex = "\\(\\d+\\)$";
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • The result still has the brackets, but that's not a problem anymore. Thank you so much! – Kovács Imre Dec 30 '13 at 20:25
  • 2
    If you don't want to have parenthesis in your result you can use `"\\((\\d+)\\)$";` and `matcher.group(1);` or you can use look-around mechanisms like `"(?<=\\()\\d+(?=\\)$)`. – Pshemo Dec 30 '13 at 20:29
  • If you want to capture numbers only in a group then you can use `String regex = "\\((\\d+)\\)$";` and then use `matcher.group(1)` to extract numbers only. OR else lookarounds as commented by @Pshemo – anubhava Dec 30 '13 at 20:30
  • 1
    Thanks, everyone. I am going to accept anubhava's answer, being first to respond. – Kovács Imre Dec 30 '13 at 20:56
3

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 not preceded 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.)

ajb
  • 31,309
  • 3
  • 58
  • 84
2

This is the required regex for your condition

\\(\\d+\\)$
Sabuj Hassan
  • 38,281
  • 14
  • 75
  • 85