Pattern与Matcher类

来源:互联网 发布:音频信号发生器软件 编辑:程序博客网 时间:2024/06/07 00:18

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子串并输出子串所在的位置。

1 0
原创粉丝点击