Java“||”字符串替换为 "OR"

Java "||" String replace by "OR"

我有一个像

这样的字符串

"age = 18 || name = 'Mistic' || civilstatus = 'married' || gender = '0' "

我需要替换“||”通过 "OR"。我尝试了以下代码。

System.out.println("age = 18 || name = 'Mistic' || civilstatus = 'married' || gender = '0'".replaceAll("||", "OR"));

但是我得到了

"ORaORgOReOR OR=OR OR1OR8OR OR|OR|OR ORnORaORmOReOR OR=OR OR'ORMORiORsORtORiORcOR'OR OR|OR|OR ORcORiORvORiORlORsORtORaORtORuORsOR OR=OR OR'ORmORaORrORrORiOReORdOR'OR OR|OR|OR ORgOReORnORdOReORrOR OR=OR OR'OR0OR'OR"

我需要的是

"age = 18 OR name = 'Mistic' OR civilstatus = 'married' OR gender = '0' "

我怎样才能做到这一点。

Edit I have read the question and answer of this question and it is not simiar. Because that question is about replacing string and my question is about getting unfamiliar result to my code.

| 在正则表达式中具有 特殊含义 。你需要逃避它。

public static void main(String[] args) {
    String s = "age = 18 || name = 'Mistic' || civilstatus = 'married' || gender = '0' ";
    System.out.println(s.replaceAll("\|\|", "OR"));
}

O/P :

age = 18 OR name = 'Mistic' OR civilstatus = 'married' OR gender = '0' 

PS :或者,您可以使用 Pattern.quote() 来转义特殊字符。

String  st = Pattern.quote("||");
System.out.println(s.replaceAll(st, "OR"));

您必须转义“||”,因为它们是正则表达式中的元字符。

使用:

System.out.println("age = 18 || name = 'Mistic' || civilstatus = 'married' || gender = '0'".replaceAll("\|\|", "OR"));

您获得的原因:

"ORaORgOReOR OR=OR OR1OR8OR OR|OR|OR ORnORaORmOReOR OR=OR OR'ORMORiORsORtORiORcOR'OR OR|OR|OR ORcORiORvORiORlORsORtORaORtORuORsOR OR=OR OR'ORmORaORrORrORiOReORdOR'OR OR|OR|OR ORgOReORnORdOReORrOR OR=OR OR'OR0OR'OR"

是因为正则表达式“||”用 "OR" 表示 "replace an empty string OR an empty string OR an empty string"。换句话说,将所有空字符串替换为 "OR".

您需要对输入字符串中的特殊字符进行转义。

您可以使用以下代码替换所有'||' "OR"

String str = "age = 18 || name = 'Mistic' || civilstatus = 'married' || gender = '0' ";
System.out.println(str.replaceAll("\|\|", "OR"));

当您不想用正则表达式替换时,为什么要使用 replaceAll

尝试使用普通 replace

System.out.println("age = 18 || name = 'Mistic' || civilstatus = 'married' 
    || gender = '0'".replace("||", "OR"));

输出

age = 18 OR name = 'Mistic' OR civilstatus = 'married' OR gender = '0'

使用Pattern.quote

System.out.println("age = 18 || name = 'Mistic' || civilstatus = 'married' || gender = '0'".replaceAll(Pattern.quote("||"), "OR"));

你可以使用replace而不是replaceAll,尝试使用以下..

    System.out.println("age = 18 || name = 'Mistic' || civilstatus = 'married' || gender = '0' ".replace("||", "OR"));