本文讲解了Java正则表达式的使用方法。
JAVA 正则表达式涉及到三个类:String,Pattern和Matcher。Pattern是要匹配的模式,Matcher是匹配的结果。例如:
Pattern p = Pattern.complie("[a-z]{3}");
Matcher m = p.mather("abc");
下面是一些常用的匹配技巧:
(1)想在正则表达式中匹配一个反斜线用四个反斜线表示: "//".matches(////);
(2)配空白行 " /n".matches("^[//s&&[^//n]]*//n$");
(3)出匹配结果在整个字符串的开始位置和结束位置
Pattern p = Pattern.complie("//d{3,5}");
String a = "123-2135-155-00";
Matcher m = p.matcher(s);
m.matches() // 匹配整个字符串,所以这里是false;
m.reset();
while(m.find()) // 找一个和这个模式所匹配的子串
{
System.out.println(m.start() + "To" + m.end());
}
(4)匹配到的java都转换成大写的
Pattern p = Pattern.complie("java", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher("java Java JaVa IloveJava You HateJaVA");
m.replaceAll("JAVA");
(5)匹配偶数个转换为大写,奇数个转换为小写
package zx.test;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TestPattern
{
public static void main(String[] args)
{
StringBuffer newString = new StringBuffer();
String isPatternString = "java Java JaVa IloveJava You HateJaVA";
Pattern p = Pattern.compile("java", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(isPatternString);
int i = 0;
while(m.find())
{
i++;
if (i % 2 == 0)
{
m.appendReplacement(newString, "java");
}
else
{
m.appendReplacement(newString, "JAVA");
}
}
m.appendTail(newString);
System.out.println(newString);
}
}
输出结果:JAVA java JAVA Ilovejava You HateJAVA
(6)Java正则表达式分组:
private static void testGroup()
{
String s = "3412afdsaf-34ijii-422342k23-423423fsdfaf";
Pattern p = Pattern.compile("(//d{1,10})([a-z]{1,9})"); // 组1:(//d{1,10}) 组2:([a-z]{1,9})
Matcher m = p.matcher(s);
while(m.find())
{
System.out.println("Group0: " + m.group() + " Group1: " + m.group(1) + " Group2: " + m.group(2));
}
}
输出结果:
Group0: 3412afdsaf Group1: 3412 Group2: afdsaf
Group0: 34ijii Group1: 34 Group2: ijii
Group0: 422342k Group1: 422342 Group2: k
Group0: 423423fsdfaf Group1: 423423 Group2: fsdfaf
新闻热点
疑难解答