Java中的模式匹配器

时间:2015-07-24 08:51:57

标签: java regex

我想要像这样的模式匹配器的结果

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++;
        }

3 个答案:

答案 0 :(得分:3)

您可以直接使用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*?)(?= - )", "<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'代表列表的第一个元素。)

我稍微改变了你的正则表达式:

  1. (\\d+)捕获多位数字(不仅仅是0-9)。此外,它“保存”在第1组
  2. 添加了符合空格符号的\\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);