2 回答

TA貢獻1804條經(jīng)驗 獲得超2個贊
基本思想是將字符串拆分為單詞,然后找出哪些單詞具有未配對的“*”。
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貢獻1864條經(jīng)驗 獲得超6個贊
有人幫我解決了這個問題:
String text1 = "*This is **my** text* ";
System.out.println(text1.replaceAll("(?<=[^*\\\\]|\\A)[*](?=[^*\\\\]|\\z)", "\\\\*"));
打印\*This is **my** text\*
添加回答
舉報