1.特殊字符
正则表达式中特殊字符的表格如下:
2.特殊字符实例学习
1).$
匹配输入字符串的结尾位置
例子:
public static void main(String[] args) {
String str="life is a fuck _movie";
//获得一个正则表达式对象
Pattern p = Pattern.compile("ie$");
//使用正则表达式对象处理指定字符串,并获得结果对象
Matcher m = p.matcher(str);
//从正则表达式结果对象中获得信息
while (true){
if(m.find()) {
System.out.print(m.group());
}else break;
}
}
2).^
匹配输入字符串的开始位置,除非在方括号表达式中使用,当该符号在方括号表达式中使用时,表示不接受该方括号表达式中的字符集合。
例子:
public static void main(String[] args) {
String str="life is a fuck _movie";
//获得一个正则表达式对象
Pattern p = Pattern.compile("^life");
//使用正则表达式对象处理指定字符串,并获得结果对象
Matcher m = p.matcher(str);
//从正则表达式结果对象中获得信息
while (true){
if(m.find()) {
System.out.print(m.group());
}else break;
}
}
3)( )
标记一个子表达式的开始和结束位置。子表达式可以获取供以后使用。
public static void main(String[] args) {
String str="life is a fuck _movie$";
//获得一个正则表达式对象
Pattern p = Pattern.compile("(i)*");
//使用正则表达式对象处理指定字符串,并获得结果对象
Matcher m = p.matcher(str);
//从正则表达式结果对象中获得信息
while (true){
if(m.find()) {
System.out.print(m.group());
}else break;
}
}
4)*
匹配前面的子表达式零次或多次。
例子:
public static void main(String[] args) {
String str="life is a fuck _movie";
//获得一个正则表达式对象
Pattern p = Pattern.compile("^life.*ie$");
//使用正则表达式对象处理指定字符串,并获得结果对象
Matcher m = p.matcher(str);
//从正则表达式结果对象中获得信息
while (true){
if(m.find()) {
System.out.print(m.group());
}else break;
}
}
5)+
匹配前面的子表达式一次或多次。
例子1:
public static void main(String[] args) {
String str="life is a fuck _movie";
//获得一个正则表达式对象
Pattern p = Pattern.compile("(lifr)+.*ie$");
//使用正则表达式对象处理指定字符串,并获得结果对象
Matcher m = p.matcher(str);
//从正则表达式结果对象中获得信息
while (true){
if(m.find()) {
System.out.print(m.group());
}else break;
}
}
例子2:
public static void main(String[] args) {
String str="life is a fuck _movie";
//获得一个正则表达式对象
Pattern p = Pattern.compile("(life)+.*ie$");
//使用正则表达式对象处理指定字符串,并获得结果对象
Matcher m = p.matcher(str);
//从正则表达式结果对象中获得信息
while (true){
if(m.find()) {
System.out.print(m.group());
}else break;
}
}
6) ?
匹配前面的子表达式零次或一次,或指明一个非贪婪限定符。
例子:
public static void main(String[] args) {
String str="life is a fuck _movie";
//获得一个正则表达式对象
Pattern p = Pattern.compile("(lifr)?.*ie$");
//使用正则表达式对象处理指定字符串,并获得结果对象
Matcher m = p.matcher(str);
//从正则表达式结果对象中获得信息
while (true){
if(m.find()) {
System.out.print(m.group());
}else break;
}
}
7)|
指明两项之间的一个选择。
例子:
public static void main(String[] args) {
String str="life is a fuck _movie";
//获得一个正则表达式对象
Pattern p = Pattern.compile("(lifr)|(life).*ie$");
//使用正则表达式对象处理指定字符串,并获得结果对象
Matcher m = p.matcher(str);
//从正则表达式结果对象中获得信息
while (true){
if(m.find()) {
System.out.print(m.group());
}else break;
}
}