替换java中的字符串中两个星号的首次出现

Gel*_*ude 0 java regex replace

我的Java,我需要替换双星号,只有第一次出现。怎么样?我要那个:

第一"**" --> "<u>" 和第二"**" --> "<\u>"

例:

String a = "John **Doe** is a bad boy"
Run Code Online (Sandbox Code Playgroud)

应该变成:

String a = "John <u>Doe<\u> is a bad boy"
Run Code Online (Sandbox Code Playgroud)

使用somethig作为:

a = a.replaceFirst("**","<u>").replaceFirst("**","<\u>")
Run Code Online (Sandbox Code Playgroud)

怎么样?

ᴇʟᴇ*_*ᴀтᴇ 5

您需要转义星号,以免将它们解释为正则表达式的一部分:

a = a.replaceFirst(Pattern.escape("**"), "<u>");
Run Code Online (Sandbox Code Playgroud)

要么:

a = a.replaceFirst("\\Q**\\E", "<u>")
Run Code Online (Sandbox Code Playgroud)

要么:

a = a.replaceFirst("\\*\\*"), "<u>");
Run Code Online (Sandbox Code Playgroud)

要执行翻译,您可以执行以下操作:

a = a.replaceAll("\\*\\*(.*?)\\*\\*", "<u>$1</u>");
Run Code Online (Sandbox Code Playgroud)

单个调用replaceAll优于一对replaceFirst调用的优点是,它replaceAll适用于包含多个星号的单词的字符串,例如"John **Doe** is a **bad** boy"

本质上,匹配表达式表示:

\\*\\*  -- 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 "**"
Run Code Online (Sandbox Code Playgroud)

更换:

<u>     -- literal <u>
$1      -- the contents of the captured group (i.e. text inside the asterisks)
</u>    -- literal </u>
Run Code Online (Sandbox Code Playgroud)

顺便说一句,我已经将您的结束标记更改为</u>而不是<\u>:-)

根据您的要求,您也许可以使用Markdown解析器(例如Txtmark),不必重新发明轮子。