ghostdog74
ghostdog74

Reputation: 342303

Java regex return after first match

how do i return after the first match of regular expression? (does the Matcher.find() method do that? )

say I have a string "abcdefgeee". I want to ask the regex engine stop finding immediately after it finds the first match of "e" for example. I am writing a method to return true/false if the pattern is found and i don't want to find the whole string for "e". (I am looking for a regex solution )

Another question, sometimes when i use matches() , it doesn't return correctly. For example, if i compile my pattern like "[a-z]". and then use matches(), it doesn't match. But when I compile the pattern as ".*[a-z].*", it matches.... is that the behaviour of the matches() method of Matcher class?

Edit, here's actually what i want to do. For example I want to search for a $ sign AND a @ sign in a string. So i would define 2 compiled patterns (since i can't find any logical AND for regex as I know the basics).

pattern1 = Pattern.compiled("$");
pattern2 = Pattern.compiled("@");

then i would just use

if ( match1.find() && match2.find()  ){
  return true;
}

in my method.

I only want the matchers to search the string for first occurrence and return.

thanks

Upvotes: 3

Views: 8387

Answers (2)

Bart Kiers
Bart Kiers

Reputation: 170148

Another question, sometimes when i use matches() , it doesn't return correctly. For example, if i compile my pattern like "[a-z]". and then use matches(), it doesn't match. But when I compile the pattern as ".[a-z].", it matches.... is that the behaviour of the matches() method of Matcher class?

Yes, matches(...) tests the entire target string.

... here's actually what i want to do. For example I want to search for a $ sign AND a @ sign in a string. So i would define 2 compiled patterns (since i can't find any logical AND for regex as I know the basics).

I know you said you wanted to use regex, but all your examples seems to suggest you have no need for them: those are all singe characters that can be handled with a couple of indexOf(...) calls.

Anyway, using regex, you could do it like this:

public static boolean containsAll(String text, String... patterns) {
    for(String p : patterns) {
        Matcher m = Pattern.compile(p).matcher(text);
        if(!m.find()) return false;
    }
    return true;
}

But, again: indexOf(...) would do the trick as well:

public static boolean containsAll(String text, String... subStrings) {
    for(String s : subStrings) {
        if(text.indexOf(s) < 0) return false;
    }
    return true;
}

Upvotes: 1

jzd
jzd

Reputation: 23629

For your second question, matches does work correctly, you example uses two different regular expressions.

.*[a-z].* will match a String that has at least one character. [a-z] will only match a one character String that is lower case a-z. I think you might mean to use something like [a-z]+

Upvotes: 2

Related Questions