java基础学习之正则表达式
java正则
java 正则有两个类Pattern和Matcher,Pattern是创建一个正则表达式
1.split
Pattern p=Pattern.compile("your regx");
p.pattern(); //得到regx
p.split(" your string");//根据正则表达式进行分割
//example
Pattern p1=Pattern.compile("\\d+");
String[] str=p1.split("我的QQ是:456456我的电话是:0532214我的邮箱是:aaa@aaa.com");
结果:str[0]="我的QQ是:" str[1]="我的电话是:" str[2]="我的邮箱是:aaa@aaa.com"
2.matches
Pattern.matches(String regex,CharSequence input)是一个静态方法,用于快速匹配字符串,该方法适合用于只匹配一次,且匹配全部字符串.
Java代码示例:
Pattern.matches("\d+","2223");//返回true
Pattern.matches("\d+","2223aa");//返回false,需要匹配到所有字符串才能返回true,这里aa不能匹配到
Pattern.matches("\d+","22bb23");//返回false,需要匹配到所有字符串才能返回true,这里bb不能匹配到
3.Matcher
Matcher 只能通过pattern.matcher("your string");获得
Pattern findPattern=Pattern.compile("\\d+");
Matcher m=findPattern.matcher("ww233aa45");```
得到matcher对象后就可以执行许多操作
第一个是三个匹配操作
* 1.matches()(其实Pattern.matches("","")等价于Pattern.compile("regx").matcher("your string").matches())
* 2.lookingAt() 对前面的字符串进行匹配,只有匹配到的字符串在最前面才返回true
* 3.find() 对字符串进行匹配,匹配到的字符串可以在任何位置.
执行这三个匹配操作之后,就可以有进一步的操作
* 1.start()返回匹配到的子字符串在字符串中的索引位置.
* 2.end()返回匹配到的子字符串的最后一个字符在字符串中的索引位置.
* 3.group()返回匹配到的子字符串

浙公网安备 33010602011771号