Find using Matcher
Pattern p = Pattern.compile("Java");
String candidateString = "I love Java2s. Java2s is about Java.";
Matcher matcher = p.matcher(candidateString);
while (matcher.find()) {
System.out.print(" " + matcher.group());
}
Java Java Java
Case-insensitive flag can be used with pattern :
Pattern p = Pattern.compile("mice", Pattern.CASE_INSENSITIVE);
Reset Matcher
Pattern p = Pattern.compile("\\d");
Matcher m1 = p.matcher("01234");
while (m1.find()) {
System.out.print(" " + m1.group());
}
m1.reset();
System.out.println("After resetting the Matcher");
while (m1.find()) {
System.out.println(" " + m1.group());
}
0 1 2 3 4
After resetting the Matcher
0 1 2 3 4
Replace all
Pattern p = Pattern.compile("(i|I)ce");
// create the candidate String
String candidateString = "I love ice. Ice is my favorite. Ice Ice Ice.";
Matcher matcher = p.matcher(candidateString);
String tmp = matcher.replaceAll("Java");
System.out.println(tmp);
I love Java. Java is my favorite. Java Java Java.
Replace first occurance
Use replaceFirst instead of replaceAll method.
String tmp = matcher.replaceFirst("Java");
I love Java. Java is my favorite. Ice Ice Ice.
Find group
String regex = "(\\w+)(\\d\\d)(\\w+)";
Pattern pattern = Pattern.compile(regex);
String candidate = "X99SuperJava";
Matcher matcher = pattern.matcher(candidate);
matcher.find();
System.out.print(matcher.group(1));
System.out.print(matcher.group(2));
System.out.print(matcher.group(3));
X 99 SuperJava
Split
Pattern pattern = Pattern.compile("ing");
String candidate = "playingrowinglaughingsleepingweeping";
Matcher matcher = pattern.matcher(candidate);
String[] str = pattern.split(input, 4);
for(String st : str) {
System.out.println(" " + st);
}
play row laugh sleepingweeping
Match with boolean result
String inputStr = "Computer";
String pattern = "Computer";
boolean patternMatched = Pattern.matches(pattern, inputStr);
System.out.println(patternMatched);
true
No comments:
Post a Comment
Note: only a member of this blog may post a comment.