Three classes covered by a JAVA regular expression:
String,pattern,matcher
Pattern is the mode to match, and Matcher is the result of the match.
For example: pattern p = Pattern.complie ("[A-z]{3}");
Matcher m = P.mather ("abc");
To match a backslash in a regular expression, use four backslashes to indicate: "\". Matches ("\");
Matches the blank line "n". Matches ("^[\s&&[^\n]]*\n$");
Finds the match result at the beginning and end of the entire string
Pattern p = Pattern.complie ("\d{3,5}");
String a = "123-2135-155-00";
Matcher m = P.matcher (s);
M.matches ()//match the entire string, so here is false;
M.reset ();
while (M.find ())//Find a substring that matches this pattern
{
System.out.println (M.start () + "to" + m.end ());
}
Converts matching Java to uppercase
Pattern p = Pattern.complie ("java", pattern.case_insensitive);
Matcher m = P.matcher ("java java java ilovejava you Hatejava");
M.replaceall ("JAVA");
Converts the number of spouses to uppercase and the odd number to lowercase
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);
}
}
Output results: Java Java java Ilovejava you Hatejava
Java Regular expression groupings:
private static void Testgroup ()
{
String s = "3412AFDSAF-34IJII-422342K23-423423FSDFAF";
Pattern p = pattern.compile ("(\d{1,10}) ([a-z]{1,9})"); Group 1: (\d{1,10}) Group 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));
}
}
Output results:
Group0:3412afdsaf group1:3412 Group2:afdsaf
Group0:34ijii group1:34 Group2:ijii
group0:422342k group1:422342 Group2:k
GROUP0:423423FSDFAF group1:423423 GROUP2:FSDFAF