Java regex return after first match

how can i return after the first regex match? (does the Matcher.find () method do this?)

Say I have an abcdefgeee line. I want to ask that the regex engine stops right after it finds the first match โ€œeโ€, for example. I am writing a method that returns true / false if a pattern is found, and I do not want to find the whole string for "e". (I'm looking for a regex)

Another question, sometimes when I use match (), it does not return correctly. For example, if I compile my template as "[az]". and then use match (), this does not match. But when I compile the template like ".*[a-z].*", it matches .... is this the behavior of the match () method of the Matcher class?

Change, thatโ€™s actually what I want to do. For example, I want to find the $ AND sign and the @ sign in a string. Therefore, I would define 2 compiled patterns (since I cannot find a logical AND for regular expression, since 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 want the matches to look for a string for the first appearance and return.

thank

+3
source share
2 answers

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

.*[a-z].*will match a string containing at least one character. [a-z]will match only the character one , which is a lowercase az. I think you could use something like[a-z]+

+2
source

, , match(), . , "[a-z]". match(), . ". [A-z].", .... match() Matcher?

, matches(...) .

... , . , $AND @ . 2 ( , ).

, , , , , , : , indexOf(...).

, regex, :

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;
}

: indexOf(...) :

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

Source: https://habr.com/ru/post/1784335/


All Articles