所有常規特殊字符#{\「} $ {「} /」,需要由\前面的常規字符串動態特殊字符escapping
input : anish$spe{cial
output : anish\$spe\{cial
input : anish}stack{overflow'
output : anish\}stack\{overflow\'
我已經用Java編寫的示例程序替換,我想更巧妙的方式
import java.util.regex.*;
import java.io.*;
/**
*
* @author anish
*
*/
public class EscapeSpecialChar {
public static void main(String[] args) throws IOException {
inputString();
}
private static void inputString() throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter string to find special characters: ");
String string = in.readLine();
// Escape the pattern
string = escapeRE(string);
System.out.println("output: -- " + string);
}
// Returns a pattern where all punctuation characters are escaped.
static Pattern escaper = Pattern.compile("([^a-zA-z0-9])");
public static String escapeRE(String str) {
return escaper.matcher(str).replaceAll("\\\\$1");
}
}
輸入字符串找到特殊字符:$Anish(Stack%1231+#$124{}
輸出: - \$Anish\(Stack\%1231\+\#\$124\{\}
有啥你的問題? –
你有什麼嘗試? 你看過http://groovy.codehaus.org/Regular+Expressions嗎?這很像你以前的問題:http://stackoverflow.com/questions/7625140/groovy-strings-with-replacing-it-by。您是否閱讀過任何Groovy文檔? –
@kevincline我試過替換('$','\\ $'),這用$替換$,但在我的情況下,在一個字符串中,我不僅有$,還有其他特殊字符,我需要逃避任何建議動態的,是的,它涉及到前面的問題,但在那裏我知道我只有$在我的Gstring中,在這個問題中我的字符串中還有其他特殊字符 – anish