特殊字符转义 [英] special character escapping
本文介绍了特殊字符转义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
输入:anish $ spe {cial
输出:anish \ $ spe \ {cial
输入:anish} stack {overflow'
输出: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(输入字符串以查找特殊字符:);
String string = in.readLine();
//转义pa ttern
string = escapeRE(string);
System.out.println(output: - + string);
}
//返回所有标点字符都被转义的模式。
static pattern escaper = Pattern.compile(([^ a-zA-z0-9]));
public static String escapeRE(String str){
return escaper.matcher(str).replaceAll(\\\\ $ 1);
$ b $ p
$ b 输入字符串以查找特殊字符: $ Anish(Stack%1231 +#$ 124 {}
输出: - \ $ Anish \\ \\(Stack \%1231\ + \#\ $ 124 \ {\}
解决方案
System.console()。with {
def inStr ='readLine'输入字符串以查找特殊字符:'
def outStr = inStr.replaceAll(/([^ a-zA-Z0-9])/,'\\\\\ $ 1')
println输出:$ outStr
}
我仍然怀疑我认为你正在做的是一个好主意,虽然......; - )
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\'
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");
}
}
Enter string to find special characters: $Anish(Stack%1231+#$124{}
output: -- \$Anish\(Stack\%1231\+\#\$124\{\}
解决方案 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屋!
查看全文