我对正则表达式概念的理解:正则表达式是对字符串操作的一种逻辑公式,根据某种规则,对字符串进行处理,从而使字符串达到自己想要的标准。
1. 匹配: 验证某字符串是否符合某项规则。
方法: str.matches(regex);
例如:验证邮箱格式是否符合要求
假设定义邮箱格式为 regex="\\w+[@][a-zA-Z]+\\.[a-zA-Z]+";
那么匹配代码如下:
public class Demo1 {
public static void main(String[] args) {
String str="123abc@qq.com";
String regex="\\w+[@][a-zA-Z]+\\.[a-zA-Z]+";
boolean b=str.matches(regex);
System.out.println(b);
}
结果为true则达到了先前定义的格式要求。
2.分割:将一字符串根据某个规则分割成若干小段
方法: str.split(regex);
例如:将字符串str="abcsfdlbeacbkid"按照分割点为"b"分割
public class Demo2 {
public static void main(String[] args) {
String str="abcsfdlbeacbkid";
String regex="b";
String[] a=str.split(regex);
for(String s:a){
System.out.println(s);
}
}
结果将会分成4段 即 a csfdl eac kid
3.替换:将字符串中某些部分替换成其他
方法: str.replaceAll(regex,newstr);
例:
public class Demo3 {
public static void main(String[] args) {
String str="abcdefg";
String regex="c";
String newstr="b";
String str1=str.replaceAll(regex,newstr);
System.out.println(str1);
}
结果为abbdefg
4.获取:获取某字符串中的信息
方法:
Pattern p = Pattern.compile
("a*b"); Matcher m = p.matcher
("aaaaab"); boolean b = m.matches
();
例:将str中三个字母的拼音提取出来
public class Demo3 {
public static void main(String[] args) {
String str="ni hao ma hao jiu bu jian ni le";
String regex="\\b[a-zA-Z]{3}\\b";
//把正则表达式封装成对象
Pattern p=Pattern.compile(regex);
//将正则表达式和要处理的字符串关联起来
//得到匹配该字符串的匹配对象
Matcher m=p.matcher(str);
//匹配
while(m.find()){
//提取匹配到的
String s=m.group();
System.out.println(s);
b=m.find();
}
}
结果: hao hao jiu