2 回答

TA贡献1804条经验 获得超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条经验 获得超6个赞
有人帮我解决了这个问题:
String text1 = "*This is **my** text* ";
System.out.println(text1.replaceAll("(?<=[^*\\\\]|\\A)[*](?=[^*\\\\]|\\z)", "\\\\*"));
打印\*This is **my** text\*
添加回答
举报