Development encountered a requirement, you need to escape all regular symbols in a piece of text, or use split split method to split the text is not valid, think of replacing to do, all replace the regular symbol is escaped after the symbol paste Java implementation code: 1. Beta
Public
Static
voidMain (string[] args) {string[] Symbols =
Newstring[] {"\\\\","\\/","\\[","\\]","\\(","\\)","\\{", "\\}","\\?","\\+","\\*","\\|","\\.","\\^","\\$","\\-","\\^" };String Text ="adasdasd| | | adasdasd| | | adasdasd| | | ADASDASD---aa ";String delimiter ="---"; //For (char C:text.tochararray ()) {//if (symbols.)// }
LongT1 = System.
Currenttimemillis ();
for(String s:symbols) {//Text = Text.replaceall (s, "\ \" + s);//Text = Pattern.compile (text). Matcher (s). ReplaceAll ("\ \" + s);//System.out.println (Pattern.compile (text, pattern.literal). Matcher (s). find ());//Text.replace (s, "\ \" + s);//System.out.println (Delimiter.indexof (s)! =-1);//if (Delimiter.indexof (s)! =-1) { the//ReplaceAll method uses a regular match, and replace is notdelimiter = Delimiter.replaceall (S,"\\"+ s);// } }
Longt2 = System.
Currenttimemillis ();System.
out. Format ("%s\n Time:%s", text, t2-t1); the//split method uses a regular matchstring[] split = Text.split (delimiter);System.
out. println (split.length); } 2. Official version /*** Escape all regular symbols * *
@params* Text *
@returnthe text after escaping */
Public
Staticstring Escaperegex (string s) {string[] Symbols =
New string[] {"\\\\","\\/","\\[","\\]", "\\(","\\)","\\{","\\}","\\?", "\\+","\\*","\\|","\\.","\\^","\\$","\\-","\\^"}; //String Text = "adasdasd| | | adasdasd| | | adasdasd| | | adasdasd---aa"; //String delimiter = s;
if (s! =
NULL) {
for(String sym:symbols) {s = S.replaceall (Sym, "\\"+ sym); } }
returns; }
Java replaces all regular symbols in text