正则表达式在Java中的应用
正则表达式其实不是Java中所独有的技术,它可以运用在很多地方比如html5中就可以使用,这里来简单描述一下正则表达式在Java中的应用
字符串匹配操作----字符串的matches()方法
注意: 字符串的匹配操作必须是完全匹配
public class Text01 {
public static void main(String[] args) {
String src = "aaaxyz123aaa";
String regex = "a{3}\\w{3}\\d{3}a{3}";
System.out.println(src.matches(regex));
}
}
代码运行结果为true
字符串替换操作----字符串的replaceAll()和replaceFirst()方法
注意: 只要字符串中有部分匹配成功即可执行替换操作
public class Text02 {
public static void main(String[] args) {
String src = "aaaxyz123aaa";
String regex = "a{3}";
System.out.println(src.replaceAll(regex, "X"));
System.out.println(src.replaceFirst(regex, "X"));
}
}
代码运行结果为:
Xxyz123X
Xxyz123aaa
字符串分割-----split() 方法
注意:字符串分割是将字符串变为空字符,然后再用逗号隔开,换句话说就是占了两个空
public class Text03 {
public static void main(String[] args) {
String src = "aaa253xyz123aaa";
String regex = "\\d{3}";
String[] strs = src.split(regex);
System.out.println(Arrays.toString(strs));
}
}
代码运行结果为:
[aaa, xyz, aaa]
字符串查找操作-----Pattern和Matcher
Pattern: 正则表达式对象
Matcher: 匹配器对象
public class Text04 {
public static void main(String[] args) {
// 将正则表达式字符串编译成正则表达式对象
Pattern p = Pattern.compile(regex);
// 通过正则表达式对象获取匹配器对象
Matcher m = p.matcher(src);
boolean matches2 = m.matches();
System.out.println(matches2);
}
}
代码结果为true