Java 正则表达式用途
- 通过pattern对象,可以对字符串进行split操作。比字符串的split方法更强大。
String testStr = "0,1,2,3,4,5,6,7-4,3-2,4-5";
String regex = "[,-]";
Pattern pattern = Pattern.compile(regex);
String[] strs = pattern.split(testStr);
- java中matcher没有findall()方法,只能通过find()进行遍历取值。
String testStr = "1234-567 589-412adf875-23";
String regex = "\\d+-\\d+";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(testStr);
while(matcher.find()) {
System.out.println(matcher.group());
}
- java中正则表达式贪婪与非贪婪模式。
String testStr = "124586-12345";;
String regex = "\\d+-\\d+";//贪婪模式 输出:124586-12345
// regex = "\\d+-\\d?"; 非贪婪模式 输出:124586-1
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(testStr);
while(matcher.find()) {
System.out.println(matcher.group());
}
- java中正则表达式后向引用。
//后向引用
String regex2 = "<h([1-6])></h\\1>";
String testStr2 = "<h2></h2>";
Pattern pattern = Pattern.compile(regex2);
Matcher matcher = pattern.matcher(testStr2);
boolean flag = matcher.matches();
- java中正则表达式后向引用替换。
//后向引用+文本替换
String testStr3 = "<h1>this is a test</h1>";
System.out.println(testStr3.replaceAll("<h1>(.*)</h1>", "<h1 color=\"red\">$1</h1>"));
- java中正则表达式正向预查。
/**
* .正向预查
* 在子模式中加入?=,表示正向预查,子模式不匹配
*/
public void test9() {
String testStr = "windows 98 windows xp windows 7";
String regex = "windows(?=[\\s]+[\\d]+\\b)";//只匹配带有数字的windows系统,且只匹配windows
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(testStr);
while(matcher.find()) {
System.out.println(matcher.group());
}
}
- java中正则表达式反向预查。
/**
* .反向预查
*/
public void test10() {
String testStr = "windows 98 windows xp windows 7";
String regex = "(?<=windows)([\\s]+[\\d]+\\b)";//只匹配带有数字的windows系统,且只匹配windows后面的数字
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(testStr);
while(matcher.find()) {
System.out.println(matcher.group());
}
}
- java中正则表达式正方向预查应用。
/**
* .正反向预查应用
* 通过正反向预查可以取出xml中标签中的内容
*/
public void test11() {
String testStr = "<h1>hello</h1><h2>world</h3>";
String regex = "(?<=<h([1-9])>).*(?=</h\\1>)";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(testStr);
while(matcher.find()) {
System.out.println(matcher.group());
}
}
- java中正则表达式负正向预查。
/**
* .负正向预查
* 在子模式中加入?!,表示负正向预查,子模式不匹配
*/
public void test9_1() {
String testStr = "windows 98 windows xp windows 7";
String regex = "windows(?![\\s]+[\\d]+\\b)";//只匹配带有字母的windows系统,且只匹配windows
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(testStr);
while(matcher.find()) {
System.out.println(matcher.group());
}
}
- java中正则表达式负反向预查。
/**
* .负反向预查
*/
public void test10_1() {
String testStr = "windows 98 windows xp windows 7";
String regex = "(?<!windows)([\\s]+[\\d]+\\b)";//只匹配带有字母的windows系统,且只匹配windows后面的数字
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(testStr);
while(matcher.find()) {
System.out.println(matcher.group());
}
}