2011-10-31 33 views
2

所有常規特殊字符#{\「} $ {「} /」,需要由\前面的常規字符串動態特殊字符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\{\}

+0

有啥你的問題? –

+0

你有什麼嘗試? 你看過http://groovy.codehaus.org/Regular+Expressions嗎?這很像你以前的問題:http://stackoverflow.com/questions/7625140/groovy-strings-with-replacing-it-by。您是否閱讀過任何Groovy文檔? –

+0

@kevincline我試過替換('$','\\ $'),這用$替換$,但在我的情況下,在一個字符串中,我不僅有$,還有其他特殊字符,我需要逃避任何建議動態的,是的,它涉及到前面的問題,但在那裏我知道我只有$在我的Gstring中,在這個問題中我的字符串中還有其他特殊字符 – anish

回答

6

這確實你的Java代碼做什麼:

System.console().with { 
    def inStr = readLine 'Enter string to find special characters: ' 
    def outStr = inStr.replaceAll(/([^a-zA-Z0-9])/, '\\\\$1') 
    println "Output: $outStr" 
} 

我仍然懷疑什麼,我認爲你做的是,雖然是個好主意... ;-)

+0

謝謝這就是我想要的, – anish

+0

確實讓我知道我怎麼能逃脫我們之間的空間,我們逃離空間的角色,它可能會混淆,即使「\」相當於「」 – anish