[英]Pattern matcher in Java
我想要这样的模式匹配器的结果
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++;
}
您可以直接使用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>");
您可以使用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. <b>$2</b> -");
}
System.out.println(finalResult);
replace all
用指定的正则表达式replace all
字符串的所有匹配项。 $1
和$2
是捕获的组(例如list的第一个元素的'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("<b>" + tokens[idx++].trim() + "</b> - " + tokens[idx++].trim() + ". ");
}
System.out.println(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.