java中要使用正则表达式首先要有一个正则表达式的表现形式,即Pattern。
通俗易懂的说法就要使用正则表达式必须有一个前提:就是必须首先将正则表达式编译为此类的实例。
然后使用它的matcher方法与要验证的字符序列进行匹配,它将返回一个Matcher匹配器。
创建匹配器后,可以使用它执行三种不同的匹配操作:
-
matches
方法尝试将整个输入序列与该模式匹配。这个相当于在字符序列头添加^ 字符序列尾部添加$ -
lookingAt
尝试将输入序列从头开始与该模式匹配。 -
find
方法扫描输入序列以查找与该模式匹配的一个子序列。这个可以理解为对字符序列的部分匹配
如果要获取匹配的子序列可以使用group方法
下面写一个部分匹配实例,从字符串中获取filename=XXXXX
public void getFileName(){
String str ="form-data; name="file1"; filename="新建文本文档.txt"";//字符序列
String reg="filename=".+"";//正则表达式
Pattern pattern =Pattern.compile(reg);
Matcher matcher = pattern.matcher(str);
if(matcher.find()){
String group = matcher.group();
System.out.println(group);
}
}