Using regular expressions in Java
JAVA.UTIL.Regex package is added to JDK1.4 to provide support for regular expressions. Moreover, the ReplaceAll and SPLIT functions in the java.lang.string class are also being implemented for regular expressions.
Regular expressions The operation of the string mainly includes: string matching, specifying string replace, specifying string lookups and string segments. Here, use an example to explain how these operations are implemented:
<% @ page import = "java.util.Regex. *"%>
<%
Pattern P = null; // Regular expression
Matcher M = NULL; // Operation String
Boolean B;
String s = null;
StringBuffer SB = NULL;
INT i = 0;
// String match, this is not in line
P = pattern.Compile ("a * b");
m = p.matcher ("baaaaab");
B = m.matches ();
Out.println (B "
");
// String match, this is in line
P = pattern.Compile ("a * b");
m = p.matcher ("aaaaab");
B = m.matches ();
Out.println (B "
");
// string replacement
P = pattern.Compile ("ab");
m = p.matcher ("aaaaab");
s = m.replaceAll ("D");
Out.println (S "
");
P = pattern.Compile ("a * b");
m = p.matcher ("aaaaab");
s = m.replaceAll ("D");
Out.println (S "
");
P = pattern.Compile ("a * b");
m = p.matcher ("caaaaab");
s = m.replaceAll ("D");
Out.println (S "
");
// String lookup
P = pattern.Compile ("cat");
M = p.matcher ("One Cat Two Cats In The Yard");
SB = new stringbuffer ();
While (M.Find ()) {
M.AppendReplacement (SB, "DOG");
i ;
}
M.AppendTail (SB);
Out.println (sb.toString () "
");
OUT.PRINTLN (i "
");
i = 0;
P = pattern.Compile ("cat");
m = p.matcher ("One Cat Two Ca Tsi Nthe Yard");
SB = new stringbuffer ();
While (M.Find ()) {
M.AppendReplacement (SB, "DOG"); i ;
}
M.AppendTail (SB);
Out.println (sb.toString () "
");
OUT.PRINTLN (i "
");
P = pattern.Compile ("cat");
M = p.matcher ("One Cat Two Cats In The Yard");
P = m.pattern ();
m = p.matcher ("bactab");
B = m.matches ();
Out.println (B "
");
s = m.ReplaceAll ("DOG");
Out.println (S "
");
i = 0;
p = pattern.Compile ("(fds) {2,}");
m = p.matcher ("DSA da fdsfds aaafdsafds aaf");
SB = new stringbuffer ();
While (M.Find ()) {
M.AppendReplacement (SB, "DOG");
i ;
}
M.AppendTail (SB);
Out.println (sb.toString () "
");
OUT.PRINTLN (i "
");
P = pattern.Compile ("cat");
M = p.matcher ("One Cat Two Cats In The Yard");
SB = new stringbuffer ();
While (M.Find ()) {
M.AppendReplacement (SB, " cat font>);
}
M.AppendTail (SB);
Out.println (sb.toString () "
");
String aa = sb.toString ();
Out.println (AA "
");
// String segmentation
P = pattern.Compile ("a ");
String [] a = p.split ("caaaaaat");
For (i = 0; i { Out.println (a [i] " } P = pattern.Compile ("a "); A = p.split ("C Aa Aaaa T", 0); For (i = 0; i { Out.println (a [i] " } P = pattern.Compile (" "); A = p.split ("C Aa Aaaa T", 0); For (i = 0; i { Out.println (a [i] " } P = pattern.Compile ("// "); A = p.split ("DSAFASDFDSAFSDA DSAGFASDFA SDAFDS"); Out.println (a.length " For (i = 0; i { Out.println (a [i] " } %>
);
);
);
);
);