2 回答
TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超2個(gè)贊
基本思想是將字符串拆分為單詞,然后找出哪些單詞具有未配對(duì)的“*”。
String text1 = "*This* is **my** text*";
String[] words = text1.split(" ");
for(int i=0; i<words.length; i++){
int count = words[i].length() - words[i].replace("*", "").length(); // count the number of '*'
if(count%2 != 0){ // if it's not paired we can replace with '\*'
words[i] = words[i].replace("*", "\\*");
}
}
System.out.println(String.join(" ", words));
Which prints out: *This* is **my** text\*
TA貢獻(xiàn)1864條經(jīng)驗(yàn) 獲得超6個(gè)贊
有人幫我解決了這個(gè)問題:
String text1 = "*This is **my** text* ";
System.out.println(text1.replaceAll("(?<=[^*\\\\]|\\A)[*](?=[^*\\\\]|\\z)", "\\\\*"));
打印\*This is **my** text\*
添加回答
舉報(bào)
