Regex to replace a string not within quotes (single or double)

后端 未结 1 1027
名媛妹妹
名媛妹妹 2020-12-15 14:40

I have a input string

this or \"that or\" or \'this or that\'

that should be translated to

this || \"th

相关标签:
1条回答
  • 2020-12-15 15:20

    Try this regex: -

    "or(?=([^\"']*[\"'][^\"']*[\"'])*[^\"']*$)"
    

    It matches or which is followed by any characters followed by a certain number of pairs of " or ', followed by a any characters till the end.

    String str = "this or \"that or\" or 'this or that'";
    str = str.replaceAll("or(?=([^\"']*[\"'][^\"']*[\"'])*[^\"']*$)", "||");        
    System.out.println(str);
    

    Output : -

    this || "that or" || 'this or that'
    

    The above regex will also replace or, if you have a mismatch of " and '.

    For e.g: -

    "this or \"that or\" or \"this or that'"
    

    It will replace or for the above strings also. If you want it not to replace in the above case, you can change the regex to: -

    str = str.replaceAll("or(?=(?:[^\"']*(\"|\')[^\"']*\\1)*[^\"']*$)", "||");
    
    0 讨论(0)
提交回复
热议问题