Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java regex first match only

Tags:

java

string

regex

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!");
            }
}
like image 603
Mark Kennedy Avatar asked Sep 16 '13 23:09

Mark Kennedy


1 Answers

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?

like image 195
ATG Avatar answered Oct 23 '22 15:10

ATG