簡體   English   中英

如何用兩個單引號替換單引號的奇數

[英]How to replace odd number of single quote with two single quote

我想在Java中的字符串中添加轉義字符"'" (單引號),但僅當使用正則表達式出現的次數奇數時

例如:

  1. 如果字符串類似於"string's property"則輸出應為"string''s property"
  2. 如果字符串類似於"string''s property"則輸出應為"string''s property"

嘗試這個 :

\'(\')?

演示(用'代替)

http://regexr.com?38eeh

試試這個代碼(偶數)。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM