简略地了解了下java.util.regex
包中的一些类,加深了对regex包使用方法的理解。
阅读了很多博客后,对regex包的大致内容有了进一步了理解
总结性的说:
(1)首先java.util.regex
包主要包含Pattern
,Matcher
,PatternSyntaxException
三个类
(2)Pattern
类代表了正则表达式,可以看作是正则表达式的编译表示
(3)Matcher
类是对输入字符串进行解释和匹配操作的引擎,根据规则进行匹配
(4)PatternSyntaxException
代表一个正则表达式中出现语法错误
分开来说:
(1)Pattern
类:
Pattern
类的构造方法是私有的。要想创建一个Pattern
对象,需要调用它的公共静态编译函数(Pattern.class中源码):
public static Pattern compile(String regex) {
return new Pattern(regex, 0);
}
而compile
函数引用了Pattern
类的私有构造函数:
private Pattern(String p, int f) {
pattern = p;
flags = f;
// to use UNICODE_CASE if UNICODE_CHARACTER_CLASS present
if ((flags & UNICODE_CHARACTER_CLASS) != 0)
flags |= UNICODE_CASE;
// Reset group index count
capturingGroupCount = 1;
localCount = 0;
if (pattern.length() > 0) {
compile();
} else {
root = new Start(lastAccept);
matchRoot = lastAccept;
}
}
这个公共静态编译函数返回了一个Pattern
对象
除此之外,还有一个参数不同的公共静态编译函数:
public static Pattern compile(String regex, int flags) {
return new Pattern(regex, flags);
}
以及相应的私有构造函数:
private Pattern(String p, int f) {
pattern = p;
flags = f;
// to use UNICODE_CASE if UNICODE_CHARACTER_CLASS present
if ((flags & UNICODE_CHARACTER_CLASS) != 0)
flags |= UNICODE_CASE;
// Reset group index count
capturingGroupCount = 1;
localCount = 0;
if (pattern.length() > 0) {
compile();
} else {
root = new Start(lastAccept);
matchRoot = lastAccept;
}
}
(2)Matcher
类
Matcher
类也没有公共的构造方法,需要通过Pattern.matcher()方法来获得Matcher
对象.
Pattern.class中:
public Matcher matcher(CharSequence input) {
if (!compiled) {
synchronized(this) {
if (!compiled)
compile();
}
}
Matcher m = new Matcher(this, input);
return m;
}
Matcher.find()函数: 返回值为布尔类型,搜索与正则表达式相符的任何子字符串,即发现CharSequence里所有匹配字符序列。find()像一个迭代器,从头到尾扫描一遍字符串
start()与end():
如果匹配成功,start( )会返回此次匹配的开始位置,end( )会返回此次匹配的结束位置,即最后一个字符的下标加一
split():
根据正则表达式将输入的字符串分割为String数组:
此处可以参考博客: Click Here
传送门:
Regex入门1 : Click Here
Regex入门2 : Click Here