本文主要测试量词和量词后缀的用法,测试的结果作为注释放在测试方法的后面。
package regularexpression; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.junit.Test; /** * 测试量词和量词后缀; * X和Y是正则表达式 * @author yuncong * */ public class TestRegularExpression2 { /** * XY表示任何X的匹配后面跟着Y的匹配 */ @Test public void test0() { String regex = "dc"; String input = "1Bdc2d"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(input); while (matcher.find()) { String output = matcher.group(); System.out.println(output); } } /** * 输出: * dc */ /** * X|Y表示任何X或Y的匹配 */ @Test public void test1() { String regex = "d|c"; String input = "1Bdc2d"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(input); while (matcher.find()) { String output = matcher.group(); System.out.println(output); } } /** * 输出: * d * c * d */ /** * X+表示1个或多个X; * 默认情况下, * 在保证匹配成功的前提下, * 匹配尽可能多的X */ @Test public void test2() { String regex = "d[a-z]+d"; String input = "1ddccBdccccd2dcd"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(input); while (matcher.find()) { String output = matcher.group(); System.out.println(output); } } /** * 输出: * dccccd * dcd */ /** * X*表示0个或多个X; * 默认情况下, * 在保证匹配成功的前提下, * 匹配尽可能多的X */ @Test public void test3() { String regex = "d[a-z]*d"; String input = "1ddccBdccccd2dcd"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(input); while (matcher.find()) { String output = matcher.group(); System.out.println(output); } } /** * 输出: * dd * dccccd * dcd */ /** * X?表示0个或1个X; * 默认情况下, * 在保证匹配成功的前提下, * 匹配尽可能多的X */ @Test public void test4() { String regex = "d[a-z]?d"; String input = "1ddccBdccccd2dcd"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(input); while (matcher.find()) { String output = matcher.group(); System.out.println(output); } } /** * 输出: * dd * dcd */ /** * 量词后缀?, * 在保证匹配成功的前提下, * 匹配尽可能多的X(?是X的量词的后缀); * 和默认情况一致 */ @Test public void test5() { String regex = "d[a-z]*?d"; String input = "1ddccBdccccd2dcd"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(input); while (matcher.find()) { String output = matcher.group(); System.out.println(output); } } /** * 输出: * dd * dccccd * dcd */ /** * 量词后缀+, * 匹配尽可能多的X(?是X的量词的后缀),即使匹配失败; */ @Test public void test6() { String regex = "d[a-z]*+d"; String input = "1ddccBdccccd2dcd"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(input); while (matcher.find()) { String output = matcher.group(); System.out.println(output); } } /** * 输出: * (没有匹配到任何字符串) */ }
原文地址:http://blog.csdn.net/l294265421/article/details/46509063