我想要像这样的模式匹配器的结果
finalResult = "1. <b>Apple</b> - Apple is a fruit 2. <b>Caw</b> - Caw is an animal 3. <b>Parrot</b> - 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), "<b>" + mat.group(count) + "</b>");
count++;
}
答案 0 :(得分:3)
您可以直接使用test.replaceAll()
而不是Pattern.matcher()
,因为replaceAll()
会自行接受正则表达式。
使用的正则表达式就像"(?<=\\d\\. )(\\w*?)(?= - )"
。
所以你的代码是
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*?)(?= - )", "<b>" + "$1" + "</b>");
答案 1 :(得分:1)
您可以使用replaceAll
类的Matcher
方法。 (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. <b>$2</b> -");
}
System.out.println(finalResult);
replace all
用指定的正则表达式替换字符串的所有匹配项。 $1
和$2
是被捕获的组(例如,'1'和'Apple'代表列表的第一个元素。)
我稍微改变了你的正则表达式:
(\\d+)
捕获多位数字(不仅仅是0-9)。此外,它“保存”在第1组\\s
符号答案 2 :(得分:0)
@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("<b>" + tokens[idx++].trim() + "</b> - " + tokens[idx++].trim() + ". ");
}
System.out.println(result);