我是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/