0

I'm working on a text to HTML parser. I'm using the "@@" notation to mark a Bold character. Ex.

Example @@Bold text in a paragraph

Turns to:

Example <strong>Bold</strong> text in paragraph

The following code works, however I've found out that it works just on the last Bold notation found:

private static String escapeBold(String sCurrentLine) {
    if (sCurrentLine.indexOf("@@") < 0) {
        return sCurrentLine;
    }

    String newString = null;
    String oldString = null;
    String chars[] = sCurrentLine.split(" ");
    for (String s : chars) {
        if (s.startsWith("@@")) {
            newString = "<strong>" + s.replaceAll("@@", "") + "</strong>";
            oldString = s;
        }
    }
    return (sCurrentLine.replaceAll(oldString, newString));
}

Is there a simpler way to do it, maybe with a RegExpr ? Thanks!

user2824073
  • 2,407
  • 10
  • 39
  • 73

1 Answers1

5

It looks like your method can look like

private static String escapeBold(String sCurrentLine) {
    return sCurrentLine.replaceAll("@@(\\w+)", "<strong>$1</strong>");
}

It will try to find each @@someWord and place someWord part in group 1. In replacement we are using match stored in group 1 via $1 and simply surrounding it with <strong> tags.

To understand this code you need to know that replaceAll(regex,replacement) uses regular expression (regex) to find part which we want to modify, and replacement describes how we want to modify it.
In regex \\w represents characters in range a-z A-Z 0-9 and _. If you want to include other characters you can create your own character class, or use \\S which represents all non-whitespace characters.

Pshemo
  • 122,468
  • 25
  • 185
  • 269