Apple - Apple is a fruit 2. Caw ...">

Template template in Java

I want to get the result from a template 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";

      

And I tried like this:

        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


source to share


3 answers


You can use test.replaceAll()

instead directly Pattern.matcher()

as it replaceAll()

takes a regex on its own.

And the regex used will look like "(?<=\\d\\. )(\\w*?)(?= - )"

.

DEMO



So the code will be

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>");

      

+3


source


You can use a replaceAll

class method Matcher

. ( javadoc )

code:

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

replaces all matches in the string with the specified regular expression. $1

and $2

are the captured groups (for example, "1" and "Apple" for the first item in the list).

I changed your regex a bit:

  • (\\d+)

    captures multi-digit numbers (not just 0-9). Also, it keeps it in group 1
  • Added characters \\s

    that match whitespace characters
+1


source


@Codebender's solution is more compact, but you can always use the method 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);

      

0


source







All Articles