![](/img/trans.png)
[英]How to replace single quote within a string with two single quotes in java?
[英]How to replace odd number of single quote with two single quote
我想在Java中的字符串中添加轉義字符"'"
(單引號),但僅當使用正則表達式出現的次數奇數時
例如:
"string's property"
則輸出應為"string''s property"
"string''s property"
則輸出應為"string''s property"
試試這個代碼(偶數)。
public static void main(String[] args) {
String str = "a''''''b";
str = str.replaceAll("[^']'('')*[^']", "###");
System.out.println(str);
}
然后嘗試這個(奇數)。
public static void main(String[] args) {
String str = "a'''''''b";
str = str.replaceAll("[^']'('')*[^']", "###");
System.out.println(str);
}
嘗試這個:
// input that will be replaced
String replace = "string's property";
// input that won't be replaced
String noReplace = "string''s property";
// String representation of the Pattern for both inputs
// |no single quote before...
// | |single quote
// | | |... no single quote after
String pattern = "(?<!')'(?!')";
// Will replace found text with main group twice --> found
System.out.println(replace.replaceAll(pattern, "$0$0"));
// Will replace found text with main group twice --> not found, no replacement
System.out.println(noReplace.replaceAll(pattern, "$0$0"));
輸出:
string''s property
string''s property
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.