用Java替换String模式

时间:2013-10-29 09:14:44

标签: java regex

我有以下字符串

"value=\"\\d{4}((((0[1-9])|(1[0-2]))((0[1-9])|([12]\\d)|(3[01]))?)?|(\\-(((0[1-9])|(1[0-2]))(\\-((0[1-9])|([12]\\d)|(3[01])))?)?)?)d{4}"

我想替换所有出现的

"{" with NCHAR(0x7B)
"}" with NCHAR(0x7D). 

"{ }"之间的内容应保持不变:

Ex: \\d{4} after replacing -> NCHAR(0x7B) 4 NCHAR(0x7D).

有没有办法在Java中使用正则表达式?

无论如何,这可以使用字符串操作处理整个字符串。

5 个答案:

答案 0 :(得分:3)

我认为您的问题不需要正则表达式,因为您想要替换每个'{'和每个'}'。你是这个意思吗?或者你是否只想在'\ d'后面替换这些字符?

theString = theString.replace("{", "NCHAR(0x7B)");
theString = theString.replace("}", "NCHAR(0x7D)");

编辑:

示例代码

public class QuickTest {
    public static void main(String args[]) {
        String theString = "toto \\d{123} 456 789";
        theString = theString.replace("{", "NCHAR(0x7B)");
        theString = theString.replace("}", "NCHAR(0x7D)");
        System.out.println(theString);
    }
}

结果

$> java QuickTest
toto \dNCHAR(0x7B)123NCHAR(0x7D) 456 789

答案 1 :(得分:1)

我同意AurélienRibon,但是如果你想使用正则表达式,你可以这样做,

String data = "value=\"\\d{4}((((0[1-9])|(1[0-2]))((0[1-9])|([12]\\d)|(3[01]))?)?|(\\-(((0[1-9])|(1[0-2]))(\\-((0[1-9])|([12]\\d)|(3[01])))?)?)?)d{4}";
data = data.replaceAll("\\{", "NCHAR(0x7B)").replaceAll("\\}","NCHAR(0x7D)");

答案 2 :(得分:0)

由于您需要替换所有出现的{},因此您可以使用replaceAll()

String theString = "\\d{4}((((0[1-9])|(1[0-2]))((0[1-9])|([12]\\d)|(3[01]))?)?|(\\-(((0[1-9])|(1[0-2]))(\\-((0[1-9])|([12]\\d)|(3[01])))?)?)?)d{4}";
theString = theString.replaceAll("{", "NCHAR(0x7B)");
theString = theString.replaceAll("}", "NCHAR(0x7D)");

答案 3 :(得分:0)

     String val = "\\d{4}((((0[1-9])|(1[0-2]))((0[1-9])|([12]\\d)|(3[01]))?)?|(\\-(((0[1-9])|(1[0-2]))(\\-((0[1-9])|([12]\\d)|(3[01])))?)?)?)d{4}";
     val = val.replace("{", "NCHAR(0x7B)");
     val = val.replace("}", " NCHAR(0x7D)"); 
     System.out.println("value::"+val);

    ------------------------------------------------------------------------

答案 4 :(得分:0)

String text = "\\\\d{4}((((0[1-9])|(1[0-2]))((0[1-9])|([12]\\d)|(3[01]))?)?|(\\-(((0[1-9])|(1[0-2]))(\\-((0[1-9])|([12]\\d)|(3[01])))?)?)?)d{4}";

    text = text.replaceAll("[{]", "NCHAR(0x7B)");
    text = text.replaceAll("[}]", "NCHAR(0x7D)");

    System.out.println(text);