Java Regex: ReplaceFirst Example and Explanation
This code snippet demonstrates the use of Java's regular expression library to replace the first occurrence of a pattern in a string.
Pattern myPattern = Pattern.compile("J.*n");
Matcher matcher = myPattern.matcher("John does this, and John does that ,and John do something");
String str = matcher.replaceFirst("sam");
System.out.println(str);
Explanation:
-
Pattern Compilation:
Pattern.compile("J.*n")creates a Pattern object representing the regular expression 'J.n'. This pattern matches any string that starts with 'J', followed by any characters (represented by '.'), and ends with 'n'.
-
Matcher Creation:
myPattern.matcher("John does this, and John does that ,and John do something")creates a Matcher object that will apply the compiled pattern to the given input string.
-
Replacing the First Occurrence:
matcher.replaceFirst("sam")replaces the first occurrence of the pattern in the input string with the string "sam".
-
Output:
System.out.println(str)prints the modified string, which is: 'sam does this, and John does that ,and John do something'.
Therefore, the correct output is B: 'sam does this, and sam does that ,and sam do something'.
原文地址: https://www.cveoy.top/t/topic/ozZJ 著作权归作者所有。请勿转载和采集!