一、前言:小组考核时,学长们又让我使用正则表达式,可惜我还是没有学会,在学长的炮轰下,我下定决心要学会正则表达式,下面就是我的学习成果:
二、正则表达式的符号的含义:
1、?:代表前面的字符可以出现一次或零次
2、*:代表前面的字符可以出现零次或多次
3、{a,b}:代表前面的字符可以出现a到b次,其中b可以省略不写,代表字符可以出现a次以上,a不可省略
4、+:代表前面的字符可以出现一次或多次
5、|:代表选择,只能我‘|’左右两边的其中一个
6、[ ]:代表的是一定的范围,例如:[abc],表示只能取自abc的其中一个或多个;[a-z],表示取自所有的小写字母,^:代表取反,取‘^’后不同的字符
7、.:代表任意字符,但不包括换行符
8、\d:代表所有的数字
9、\w:代表所有的单词字符,包括数字,字母,下划线
10、 \s:代表空白符,包括tab键和换行符
11、\b:代表匹配隐式位置上述的表达式的字母如果大写就代表与原来的相反
12、^:代表匹配行首 13、 $:代表匹配行尾
三、在Java中的使用:
1、按指定模式在字符串查找
2、创建 Pattern 对象
3、创建 matcher 对象
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexMatches
{
public static void main( String[] args ){
// 按指定模式在字符串查找
String line = "This order was placed for QT3000! OK?";
String pattern = "(\\D*)(\\d+)(.*)";
// 创建 Pattern 对象
Pattern r = Pattern.compile(pattern);
// 现在创建 matcher 对象
Matcher m = r.matcher(line);
if (m.find( )) {
System.out.println("Found value: " + m.group(0) );
System.out.println("Found value: " + m.group(1) );
System.out.println("Found value: " + m.group(2) );
System.out.println("Found value: " + m.group(3) );
} else {
System.out.println("NO MATCH");
}
}
}
输出结果: Found value: This order was placed for QT3000! OK? Found value: This order was placed for QT Found value: 3000 Found value: ! OK?
在 Java 中,\\ 表示:我要插入一个正则表达式的反斜线,所以其后的字符具有特殊的意义。
当然,在Java中正则表达式还有许多其他的方法,像matches 和 lookingAt 方法等。
matches 和 lookingAt 方法都用来尝试匹配一个输入序列模式。它们的不同是 matches 要求整个序列都匹配,而lookingAt 不要求。lookingAt 方法虽然不需要整句都匹配,但是需要从第一个字符开始匹配。
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexMatches
{
private static final String REGEX = "foo";
private static final String INPUT = "fooooooooooooooooo";
private static final String INPUT2 = "ooooofoooooooooooo";
private static Pattern pattern;
private static Matcher matcher;
private static Matcher matcher2;
public static void main( String[] args ){
pattern = Pattern.compile(REGEX);
matcher = pattern.matcher(INPUT);
matcher2 = pattern.matcher(INPUT2);
System.out.println("Current REGEX is: "+REGEX);
System.out.println("Current INPUT is: "+INPUT);
System.out.println("Current INPUT2 is: "+INPUT2);
System.out.println("lookingAt(): "+matcher.lookingAt());
System.out.println("matches(): "+matcher.matches());
System.out.println("lookingAt(): "+matcher2.lookingAt());
}
}
输出结果为:
Current REGEX is: foo Current INPUT is: fooooooooooooooooo Current INPUT2 is: ooooofoooooooooooo lookingAt(): true matches(): false lookingAt(): false
四、总结:学习过正则表达式之后感觉其还是很实用的,我会在以后经常使用的,力争完全掌握,加油!!!奥里给!!!