Java中的模式匹配器 [英] Pattern matcher in Java
本文介绍了Java中的模式匹配器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想要一个像这样的模式匹配器的结果
I want a result from a pattern matcher like this
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()
自己接受正则表达式。
You can directly use test.replaceAll()
instead of using Pattern.matcher()
, since replaceAll()
accepts regex on its own.
使用的正则表达式就像(?< = \\ d \\。)(\\\\ * *)(?= - )
。
And the regex to use would be like "(?<=\\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>");
这篇关于Java中的模式匹配器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文