You need to escape the asterisks to avoid them being interpreted as part of a regular expression:
a = a.replaceFirst(Pattern.escape("**"), "<u>");
Or:
a = a.replaceFirst("\\Q**\\E", "<u>")
Or:
a = a.replaceFirst("\\*\\*"), "<u>");
To perform your translation you could do this:
a = a.replaceAll("\\*\\*(.*?)\\*\\*", "<u>$1</u>");
The advantage of a single replaceAll
over a pair of replaceFirst
calls is that replaceAll
would work for strings containing multiple asterisked words, e.g. "John **Doe** is a **bad** boy"
.
Essentially the matching expression means:
\\*\\* -- literal "**"
( -- start a capturing group
. -- match any character (except LF, CR)
* -- zero or more of them
? -- not greedily (i.e. find the shortest match possible)
) -- end the group
\\*\\* -- literal "**"
The replacement:
<u> -- literal <u>
$1 -- the contents of the captured group (i.e. text inside the asterisks)
</u> -- literal </u>
By the way, I've changed your end tag to </u>
instead of <\u>
:-)
Depending on your requirements, you might be able to use a Markdown parser, e.g. Txtmark and save yourself reinventing the wheel.