2

If I want to match the following pattern like

[black]something[/black] [orange]something[/orange]

and change them to HTML Code <span style="color:black">something</span>

But not change those not paired like [black]hello[/orange]

How can I write the regular expression to recognize them?

manlio
  • 18,345
  • 14
  • 76
  • 126
benleung
  • 871
  • 4
  • 12
  • 25
  • You want to parse only the BB color codes, or other BB codes as well? – Raptor Jul 29 '13 at 02:30
  • possible duplicate of [Java BBCode library](http://stackoverflow.com/questions/849396/java-bbcode-library) – Raptor Jul 29 '13 at 02:31
  • @ShivanRaptor only BB color codes at this moment, some codes I have been parsed and some maybe parse it later. – benleung Jul 29 '13 at 02:32
  • Maybe you can look into the question I quoted above. They already found solution. – Raptor Jul 29 '13 at 02:32
  • @ShivanRaptor But my BB color code is not written in `[color=black]something[/color]`, It written in `[black]blah blah[/black]` like this. – benleung Jul 29 '13 at 02:34
  • You can add few more cases to the solution. – Raptor Jul 29 '13 at 02:35
  • @ShivanRaptor What I am going to ask is that how to write a regular expression that only match `[black]blah blah[/black]` but `[black]blah blah[/orange]` – benleung Jul 29 '13 at 02:37
  • Maybe you should try it yourself to change codes, instead of keep asking. – Raptor Jul 29 '13 at 02:39
  • What regular expressions have you tried and what were the problems you encountered? – Diego Torres Milano Jul 29 '13 at 02:39
  • @dtmilano actually I wanna find out a regular expression which represent the same keywords like "black" must show up in correct position and twice only – benleung Jul 29 '13 at 02:51

2 Answers2

1

Here is the solution, as mentioned in comments:

public static String bbcode(String text) {
    String html = text;

    Map<String,String> bbMap = new HashMap<String , String>();

    bbMap.put("\\[black\\](.+?)\\[/black\\]", "<span style='color: black;'>$1</span>");
    bbMap.put("\\[orange\\](.+?)\\[/orange\\]", "<span style='color: orange;'>$1</span>");
    // add other colors

    for (Map.Entry entry: bbMap.entrySet()) {
        html = html.replaceAll(entry.getKey().toString(), entry.getValue().toString());
    }

    return html;
}
Raptor
  • 53,206
  • 45
  • 230
  • 366
1

Use KefirBB. It's configurable opensource library for text translations.

http://kefirsf.org/kefirbb/