正则表达式是一中强大而灵活的文本处理工具。使用正则表达式,我们能以变成的方式,构造复杂的文本模式,并对输入的字符串进行搜索。
第一种用法是在String类型中直接调用方法
import java.util.Arrays;
public class String_match {
public static void main(String[] args) {
//判断1234是否符合正则表达式“-?\\d+”
System.out.println("-1234".matches("-?\\d+"));
//split方法
String str1="I am a good student! who you are?";
String[] str2=str1.split(" ");
System.out.println(Arrays.toString(str2));//空格分开
System.out.println(Arrays.toString(str1.split(" ",2)));//空格分开,限制分割两次
System.out.println(Arrays.toString(str1.split("\\W+")));//非字符分割
//replace和replaceall
System.out.println(str1.replaceFirst(" |o", "_"));
System.out.println(str1.replaceAll(" |o", "_"));
}
}
输出为
true
[I, am, a, good, student!, who, you, are?]
[I, am a good student! who you are?]
[I, am, a, good, student, who, you, are]
I_am a good student! who you are?
I_am_a_g__d_student!_wh__y_u_are?
第二种用法直接构造强大的正则表达式对象
导入java.util.regex包,然后用static Pattern.compile()方法编译你的正则表达式即可
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TestRegularExpression {
public static void main(String[] args) {
Pattern p=null;
Matcher m=null;
//组的概念
p = Pattern.compile("cardgroupid=S(\\d{0,})");
m = p.matcher("chaincardlist.mc?cardgroupid=S5");
System.out.println(m.find());
p = Pattern.compile("^searchcardlist\\.v2\\.mc\\?cityid=(\\d{1,})\\®ionid=(\\d{1,})");
m = p.matcher("searchcardlist.v2.mc?cityid=2®ionid=22");
if (m.matches()) {
String a=m.group(0);
System.out.println(m.group(0));
System.out.println(m.group(1));
System.out.println(m.group(2));
}
//find方法/reset方法、replace方法
int count=0;
p=Pattern.compile("\\d{1,}");
m=p.matcher("searchcardlist?cardid=9");
while(m.find()){
System.out.println(m.replaceAll("S9"));
}
m.reset("searchcardlist?cardid=9&userid=10");
while(m.find()){
System.out.println(m.replaceAll("d99"));
}
}
}
点击运行,输出结果为
true
searchcardlist.v2.mc?cityid=2®ionid=22
2
22
searchcardlist?cardid=S9
searchcardlist?cardid=d99&userid=d99
各位看官儿,到此您对正则表达式有一定的了解了吧。希望如此。本人平有限,时间有限,只能写到此了。