Java正则匹配替换
Java提供了一些方法来执行正则表达式的匹配和替换。以下是一些常用的方法:
matches(String regex, CharSequence input):用指定的正则表达式匹配给定的输入字符串。如果整个输入字符串与正则表达式匹配,返回true;否则返回false。
示例:
String input = "hello world";
boolean match = input.matches(".*world.*");
System.out.println(match); // true
Pattern.compile(String regex):将给定的正则表达式编译成一个Pattern对象,用于匹配和替换。
示例:
String input = "hello world";
Pattern pattern = Pattern.compile("world");
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
System.out.println(matcher.group()); // world
}
Matcher.replaceAll(String replacement):使用指定的替换字符串替换匹配的子串,并返回新的字符串。
示例:
String input = "hello world";
Pattern pattern = Pattern.compile("world");
Matcher matcher = pattern.matcher(input);
String result = matcher.replaceAll("Java");
System.out.println(result); // hello Java
String.replaceAll(String regex, String replacement):使用指定的替换字符串替换匹配的子串,并返回新的字符串。
示例:
String input = "hello world";
String result = input.replaceAll("world", "Java");
System.out.println(result); // hello Java
String.replaceFirst(String regex, String replacement):使用指定的替换字符串替换第一个匹配的子串,并返回新的字符串。
示例:
String input = "hello world";
String result = input.replaceFirst("world", "Java");
System.out.println(result); // hello Java
原文地址: https://www.cveoy.top/t/topic/bgmn 著作权归作者所有。请勿转载和采集!