Java 正则查找/替换/分割操作
![](https://i-blog.csdnimg.cn/direct/60168152aff6430982bc762fd335e2f0.png)
正则查找
Matcher matcher = Pattern.compile("播放|暂停|停止").matcher("当前暂停音乐");
if(matcher.find()){
System.out.println(matcher.group(0));
}
if(Pattern.compile("播放|暂停|停止").matcher("当前停音乐").find()){
System.out.println("查找到");
}
package cn.netkiller;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("www|netkiller");
Matcher matcher = pattern.matcher("http://www.netkiller.cn/linux/index.html");
if (matcher.find()) {
System.out.println(matcher.group());
}
}
}
正则替换
package cn.netkiller;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("www|netkiller");
Matcher matcher = pattern.matcher("https://www.netkiller.cn/linux/index.html");
if (matcher.find()) {
String s = matcher.replaceFirst("api"); //替换后的字符串
System.out.println(s);
}
}
}
package cn.netkiller;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("www|netkiller");
Matcher matcher = pattern.matcher("https://www.netkiller.cn/linux/index.html");
if (matcher.find()) {
String s = matcher.replaceAll("test"); //替换后的字符串
System.out.println(s);
// 输出结果:https://test.test.cn/linux/index.html
}
}
}
"aab".replaceAll("a{1}", "x"); //xxb
"aba".replaceAll("a{1}", "x"); //xbx
"abaaabaaaba".replaceAll("a{2}", "x"); //abxabxaba
"abaabaaaaba".replaceAll("a{2}", "x"); //abxbxxba
字符串分割
String input = "苹果!!香蕉!!鸭梨!!橘子";
System.out.println(Arrays.toString(Pattern.compile("!!").split(input)));
System.out.println(Arrays.toString(Pattern.compile("!!").split(input, 3)));
[苹果, 香蕉, 鸭梨, 橘子]
[苹果, 香蕉, 鸭梨!!橘子]