I have the following string
"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}"
There I want to replace all the occurrences of
"{" with NCHAR(0x7B)
"}" with NCHAR(0x7D).
An the content in-between "{ }" should remain unchanged:
Ex: \\d{4} after replacing -> NCHAR(0x7B) 4 NCHAR(0x7D).
Is there a way to do this using Regular Expressions in Java?.
Anyway, this can be done processing the whole string using string operations.
-
Are you sure '\\d{4}' should not become '\\d NCHAR(0x7B) 4 NCHAR(0x7D)'?Aurelien Ribon– Aurelien Ribon2013年10月29日 09:33:25 +00:00Commented Oct 29, 2013 at 9:33
5 Answers 5
I do not see any need for a regexp in your issue, since you want to replace every '{' and every '}'. Is that what you mean? Or do you want to replace these character only when then are behind a '\d'?
theString = theString.replace("{", "NCHAR(0x7B)");
theString = theString.replace("}", "NCHAR(0x7D)");
EDIT:
Sample code
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);
}
}
Result
$> java QuickTest
toto \dNCHAR(0x7B)123NCHAR(0x7D) 456 789
1 Comment
I agree with Aurélien Ribon, however if you want to use regex you could do it like this,
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)");
Comments
Since you need to replace all occurrences of { and }, you can use 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)");
Comments
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);
------------------------------------------------------------------------
Comments
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);