特殊角色逃脱

时间:2011-10-31 03:27:36

标签: groovy

所有常规特殊字符#{\'} $ {“} /',需要在一个groovy字符串中被\替换为

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\{\}

1 个答案:

答案 0 :(得分:7)

这就是你的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"
}

我仍然怀疑我认为你在做什么虽然是好主意...; - )