您的位置:首页 > 编程语言 > Java开发

Pattern与Matcher类

2017-04-18 20:40 113 查看
Java提供了专门用来进行模式匹配的Pattern类和Matcher类,这些类在java.util.regex包中。

模式对象

pattern p = Pattern.compile("abc");//Pattern类调用compile(String regex)返回一个模式对象,其中regex是一个正则表达式。如果参数regex指定的正则表达式有错,compile方法将抛出异常PatternSyntaxException。
匹配对象

Matcher m = p.matcher(s);//模式对象调用matcher(CharSequence input)方法返回一个Matcher对象
代码示例

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
public static void main(String[] args) {
String regex = "abc";
Pattern p = Pattern.compile(regex);
String s = "abcdf abcgh abc abc 123as";
Matcher m = p.matcher(s);
while(m.find()){
String str = m.group();
System.out.print("从"+m.start()+"到"+m.end()+"匹配模式子序列:");
System.out.println(str);
}
}
}输出结果为:
从0到3匹配模式子序列:abc
从6到9匹配模式子序列:abc
从12到15匹配模式子序列:abc
从16到19匹配模式子序列:abc

代码解释
上面这个示例代码实现了在字符串s中找regex子串并输出子串所在的位置。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息