14

How do I tell the following regex to only find the FIRST match? The following code keeps finding all possible regex within the string.

i.e. I'm looking only for the indices of the substring (200-800;50]

public static void main(String[] args) {

    String regex = "(\\[|\\().+(\\]|\\))";

    String testName=  "DCGRD_(200-800;50]MHZ_(PRE|PST)_(TESTMODE|REG_3FD)";

            Pattern pattern = 
            Pattern.compile(regex);

            Matcher matcher = 
            pattern.matcher(testName);

            boolean found = false;

            while (matcher.find()) {
                System.out.format("I found the text" +
                    " \"%s\" starting at " +
                    "index %d and ending at index %d.%n",
                    matcher.group(),
                    matcher.start(),
                    matcher.end());
                found = true;

            }

            if (!found){
                System.out.println("Sorry, no match!");
            }
}
3
  • 1
    The first match would be the first iteration of your loop. Just process one iteration and that's it. Or don't have a loop at all, and simply process the match if find returns true. Commented Sep 16, 2013 at 23:23
  • Your regex matches (200-800;50]MHZ_(PRE|PST)_(TESTMODE|REG_3FD). Are you in need of help with the regex? Commented Sep 16, 2013 at 23:56
  • I only needed the first occurrence. i.e (200-800;50]. Got it all squared away! :) Commented Sep 18, 2013 at 1:25

1 Answer 1

15

matcher.group(1) will return the first match.

If you mean lazy matching instead of eager matching, try adding a ? after the + in the regular expression.

Alternatively, you can consider using something more specific than .+ to match the content between the brackets. If you're only expecting letters, numbers and a few characters then maybe something like [-A-Z0-9;_.]+ would work better?

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

3 Comments

What matcher.group(1) returns is the contents of the first capturing group, (\[|\(). So it will be ( or [, and in this particular example it would always be ( because all three of the possible matches start with that. (group(2) will return ]` or ).) Anyway, the reluctant-or-more-specific advice seems to be what the OP was looking for, so +1.
Wait... Shouldn't matcher.group(0) return the first match?
You might think that intuitively, but group 0 actually returns the whole matched expression.

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.