class Regex1{ public static void main(String args[]) { String str="For my money, the important thing "+"about the meeting was bridge-building"; String regEx="a|f"; //表示a或f Pattern p=Pattern.compile(regEx); Matcher m=p.matcher(str); boolean result=m.find(); System.out.println(result); } } 如果str匹配regEx,那么result为true,否则为flase。如果想在查找时忽略大小写,则可以写成:
生成字符串的字符串——正则表达式,真有些复杂,因为我们希望由普通字符(例如字符 a 到 z)以及特殊字符(称为元字符)描述任意的字符串,而且要准确。
先看几个正则表达式例子:
程序3:我们总用这个程序测试正则表达式。
import java.util.regex.*;
class Regex1{ public static void main(String args[]) { String str="For my money, the important thing "; String regEx="ab*"; boolean result=Pattern.compile(regEx).matcher(str).find(); System.out.println(result); } }//ture ①"ab*"——能匹配a、ab、abb、abbb……。所以,*表示前面字符可以有零次或多次。如果仅仅考虑查找,直接用"a"也一样。但想想替换的情况。 问题regEx="abb*"结果如何?