简体   繁体   中英

Pattern Java - Regular Expression

I need to do a college exercise that is as follows: Validate with regular expressions any word that contains exactly two 'a' characters and two 'b' characters or more. I made the following expression in the Pattern class:

Pattern pattern = Pattern.compile("a{2}b{2,}");

This pattern only validates expressions that begin with two 'a' characters and then two or more 'b' characters. But the exercise requires that the two characters a can be anywhere in the sentence and not necessarily at the beginning, as well as the 'b' characters. How do I do this regular expression

Resolution

(a.*){2}b.*b|(b.*){2}a.*a|(a.*b|b.*a){2}

Explanation

(a.*){2}b.*b search for sentences that have a followed by a , after b followed by b .

(b.*){2}a.*a search for sentences that have b followed by b , after a followed by a .

(a.*b|b.*a){2} search a followed by b ou b followed by a .

From Pattern you get a Matcher , which has two methods:

public boolean matches()

Attempts to match the entire region against the pattern.

public boolean find()

Attempts to find the next subsequence of the input sequence that matches the pattern.

This method starts at the beginning of this matcher's region, or, if a previous invocation of the method was successful and the matcher has not since been reset, at the first character not matched by the previous match.

You may use your original pattern and just call find instead of matches :

Pattern pattern = Pattern.compile("a{2}b{2,}");
Matcher matcher = pattern.matcher(myStringToBeSearchedForPattern);
if (matcher.find()) {
   System.out.println("Found!");
}

However, depending on the requirements you have to modify your pattern. From your description it is unclear what the exact requirements are (Can a{2} and b{2,} be in any order? Are there other characters then a and b ?)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM