Java中的模式匹配器
我想要一个像这样的模式匹配器的结果
finalResult = "1. Apple - Apple is a fruit 2. Caw - Caw is an animal 3. Parrot - Parrot is a bird";
我试过这样的方式:
String test = "1. Apple - Apple is a fruit 2. Caw - Caw is an animal 3. Parrot - Parrot is a bird"; String finalResult = ""; Pattern pat = Pattern.compile("\\d\\.(.+?)-"); Matcher mat = pat.matcher(test); int count = 0; while(mat.find()){ finalResult += test.replaceAll(mat.group(count), "" + mat.group(count) + ""); count++; }
您可以直接使用test.replaceAll()
而不是使用Pattern.matcher()
,因为replaceAll()
自己接受正则表达式。
要使用的正则表达式就像"(?<=\\d\\. )(\\w*?)(?= - )"
。
DEMO
所以你的代码就是
String test = "1. Apple - Apple is a fruit 2. Caw - Caw is an animal 3. Parrot - Parrot is a bird"; String finalResult = ""; finalResult = test.replaceAll("(?<=\\d\\. )(\\w*?)(?= - )", "" + "$1" + "");
您可以使用Matcher
类的replaceAll
方法。 ( javadoc )
码:
String test = "1. Apple - Apple is a fruit 2. Caw - Caw is an animal 3. Parrot - Parrot is a bird"; String finalResult = ""; Pattern pat = Pattern.compile("(\\d+)\\.\\s(.+?)\\s-"); Matcher mat = pat.matcher(test); if (mat.find()){ finalResult = mat.replaceAll("$1. $2 -"); } System.out.println(finalResult);
用指定的正则表达式replace all
替换字符串的所有匹配项。 $1
和$2
是捕获的组(例如’1’和’Apple’代表列表的第一个元素)。
我稍微改变了你的正则表达式:
-
(\\d+)
捕获多位数字(不仅仅是0-9)。 此外,它将其“保存”在第1组中 - 添加了匹配空格符号的
\\s
符号
@Codebender的解决方案更紧凑,但你总是可以使用String.split()
方法:
String test = "1. Apple - Apple is a fruit 2. Caw - Caw is an animal 3. Parrot - Parrot is a bird"; String[]tokens = test.split("-\\s*|\\d\\.\\s*"); StringBuffer result = new StringBuffer(); int idx = 1; while (idx < (tokens.length - 1)) { result.append("" + tokens[idx++].trim() + " - " + tokens[idx++].trim() + ". "); } System.out.println(result);