java - 替换java中字符串中第一次出现的两个星号

标签 java regex replace

我是java,我需要替换双星号,只有第一次出现。如何? 我想要那个:

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

示例:

String a = "John **Doe** is a bad boy"

应该变成:

String a = "John <u>Doe<\u> is a bad boy"

使用一些东西作为:

a = a.replaceFirst("**","<u>").replaceFirst("**","<\u>")

如何?

最佳答案

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

a = a.replaceFirst(Pattern.escape("**"), "<u>");

或者:

a = a.replaceFirst("\\Q**\\E", "<u>")

或者:

a = a.replaceFirst("\\*\\*"), "<u>");

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

a = a.replaceAll("\\*\\*(.*?)\\*\\*", "<u>$1</u>");

单的优势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 "**"

替换:

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

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

根据您的要求,您也许可以使用 Markdown 解析器,例如Txtmark并避免重新发明轮子。

关于java - 替换java中字符串中第一次出现的两个星号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23545324/

相关文章:

Java在方法中将全局变量转换为局部变量的优点

java - Spring MVC 中 POST 方法后重定向

java - 我可以将 JWT 授权从 spring RestController 传递到外部后端 API

java - 是否可以通过 spout 或 bolt 停用和重新激活 Storm 拓扑?

java - 替换java中序列的所有实例

javascript - 更改图像的部分 URL 字符串

c - 用字符串中的单个 'a' 替换三个 '*'

javascript - AngularJs ng-模式正则表达式

c++ - 正则表达式 : Alphanumeric strings with constraints

linux - 如何使用 awk、sed 等 Linux 命令删除文本 block 中双引号之间的所有空格