jdk1.4中加入了java.util.regex包提供对正则表达式的支持。而且java.lang.string类中的replaceall和split函数也是调用的正则表达式来实现的。
正则表达式对字符串的操作主要包括:字符串匹配,指定字符串替换,指定字符串查找和字符串分割。下面就用一个例子来说明这些操作是如何实现的:
| <%@ page import="java.util.regex.*"%> <% pattern p=null; //正则表达式 matcher m=null; //操作的字符串 boolean b; string s=null; stringbuffer sb=null; int i=0; //字符串匹配,这是不符合的 p = pattern.compile("a*b"); m = p.matcher("baaaaab"); b = m.matches(); out.println(b+" "); //字符串匹配,这是符合的 p = pattern.compile("a*b"); m = p.matcher("aaaaab"); b = m.matches(); out.println(b+" "); //字符串替换 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+" "); //字符串查找 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("bacatab"); 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, "<font color=/"red/">cat</font>"); } m.appendtail(sb); out.println(sb.tostring()+" "); string aa=sb.tostring(); out.println(aa+" "); //字符串分割 p = pattern.compile("a+"); string[] a=p.split("caaaaaat"); for(i=0;i<a.length;i++) { out.println(a[i]+" "); } p = pattern.compile("a+"); a=p.split("c aa aaaa t",0); for(i=0;i<a.length;i++) { out.println(a[i]+" "); } p = pattern.compile(" +"); a=p.split("c aa aaaa t",0); for(i=0;i<a.length;i++) { out.println(a[i]+" "); } p = pattern.compile("//+"); a=p.split("dsafasdfdsafsda+dsagfasdfa+sdafds"); out.println(a.length+" "); for(i=0;i<a.length;i++) { out.println(a[i]+" "); } %> |
闽公网安备 35060202000074号