替换java中String中第一次出现的两个星号

时间:2014-05-08 14:53:02

标签: java regex replace

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

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

示例:

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

应该成为:

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

使用somethig作为:

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

如何?

4 个答案:

答案 0 :(得分:4)

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

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并拯救自己重新发明轮子。

答案 1 :(得分:1)

您可以使用:

String a = "John **Doe** is a bad boy"
a = a.replaceFirst("\\Q**\\E", "<u>").replaceFirst("\\Q**\\E", "</u>");
//=> John <u>Doe</u> is a bad boy

答案 2 :(得分:0)

正如上面提到的aetheria并与你已经尝试过的一样:

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

当你想尝试别的东西时,我建议使用下面的在线正则表达式测试器,它将在不同的输入字符串上使用replaceFirst,replaceAll等显示不同模式的结果。它还将在左上角提供应在Java代码中使用的正确转义的字符串。

http://www.regexplanet.com/advanced/java/index.html

答案 3 :(得分:0)

我会这样做:

String a = "John **Doe** is a bad boy";
String b = a.replaceAll("\\*\\*(.*?)\\*\\*", "<u>$1</u>");
//John <u>Doe</u> is a bad boy

LIVE DEMO

REGEX EXPLANATION

\*\*(.*?)\*\*

Match the character “*” literally «\*»
Match the character “*” literally «\*»
Match the regex below and capture its match into backreference number 1 «(.*?)»
   Match any single character that is NOT a line break character (line feed, carriage return, next line, line separator, paragraph separator) «.*?»
      Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Match the character “*” literally «\*»
Match the character “*” literally «\*»

<u>$1</u>

Insert the character string “<u>” literally «<u>»
Insert the text that was last matched by capturing group number 1 «$1»
Insert the character string “</u>” literally «</u>»