Java正则
例题 字符串由a或b组成,匹配首尾相同的字符串
String reg = "([ab])([ab]*\\1)?"
\\1
中的\\
是Java的转义\
,\1
指代第一个括号中的内容。第一个括号是表示第一个字符的匹配,第二个括号是用来匹配从第二开始到结尾的字符,并且最后一个字符要匹配第一个字符。第二个括号用?
修饰,可以适配只有一个字符的情况。
寻找正则匹配子串
1.设定正则表达式String regex
2.使用Pattern
类编译正则表达式
3.调用Pattern
对象的matcher(reg)
方法返回一个Matcher
对象
4.Matcher
对象调用find()
方法可以进行匹配
5.匹配后可以通过matcher.start(),matcher.end()
进行substring()
。也可以直接通过matcher.group()
返回匹配字符串。
String regex = "([ab])([ab]*\\1)?";
Pattern p = Pattern.compile(regex);
String str = "abbab";
Matcher m = p.matcher(str);
while(m.find()) {
String foundStr = str.substring(m.start(), m.end());
String foundStr2 = m.group();
System.out.println(foundStr);
}
// 输出
abba
b
字符串是否匹配正则
String regex = "([ab])([ab]*\\1)?"
String str = "abbab";
if(str.matches(regex)) {
System.out.println("true");
} else {
System.out.println("false");
}
// 输出
false