特殊字符转义 [英] Special character escaping

查看:100
本文介绍了特殊字符转义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所有groovy特殊字符#{\'} $ {}/',需要动态替换为groovy字符串中前面的\

All groovy special character #{\'}${"}/', needs to be replaced by \ in front in a groovy string dynamically

input  : anish$spe{cial
output : anish\$spe\{cial
input  : anish}stack{overflow'
output : anish\}stack\{overflow\'

我已经用Java编写了一个示例程序,希望以更简单的方式

I have written a sample program in Java, that i want in groovier way

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

Enter string to find special characters: $Anish(Stack%1231+#$124{}

输出:-\$Anish\(Stack\%1231\+\#\$124\{\}

推荐答案

这可以完成您的Java代码:

This does what your Java code does:

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

我仍然怀疑我的想法是一个好主意...;-)

I am still dubious that what I think you are doing is a good idea though... ;-)

这篇关于特殊字符转义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆