JAVA 正則表達式涉及的三個類:
String,Pattern,Matcher
Pattern是要匹配的模式,Matcher是匹配的結果.
例如:Pattern p = Pattern.complie("[a-z]{3}");
Matcher m = p.mather("abc");
要想在正則表達式中匹配一個反斜線用四個反斜線表示: "
\\".matches("\\\\");
匹配空白行 " \n".matches("^[\\s&&[^\\n]]*\\n$");
找出匹配結果在整個字符串的開始位置和結束位置
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());
}
將匹配到的java都轉換成大寫的
Pattern p = Pattern.complie("java", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher("java Java JaVa IloveJava You HateJaVA");
m.replaceAll("JAVA");
將匹配偶數個轉換爲大寫,奇數個轉換爲小寫
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
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