如何在 Java 中一次性从整个字符串中转义所有特殊字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22031329/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 13:10:08  来源:igfitidea点击:

How to escape all Special Characters from whole string at one go in Java

javalucene

提问by gozizibj

Lucene supports escaping special characters that are part of the query syntax. The current list special characters are

Lucene 支持转义作为查询语法一部分的特殊字符。当前列表特殊字符是

+ - && || ! ( ) { } [ ] ^ " ~ * ? : \

To escape these character use the \ before the character. For example to search for (1+1):2 use the query:

要转义这些字符,请在字符前使用 \。例如要搜索 (1+1):2 使用查询:

\(1\+1\)\:2

My question is how to escape from whole string at one go?For example myStringToEscape = "ABC^ " ~ * ? :DEF";How to get a escapedString.

我的问题是如何一次从整个字符串中逃脱?例如myStringToEscape = "ABC^ " ~ * ? :DEF";如何获得一个escapedString

回答by femtoRgon

You can use QueryParser.escape, such as:

您可以使用QueryParser.escape,例如:

String escapedString = queryParser.escape(searchString);
queryParser.parse("field:" + escapedString);

回答by ADDruid

If you are just looking for simple replacement, this will do the trick.

如果您只是在寻找简单的替代品,这可以解决问题。

String regex = "([+\-!\(\){}\[\]^\"~*?:\\]|[&\|]{2})";

String myStringToEscape = "ABC^ \" ~ * ? :DEF";
String myEscapedString = myStringToEscape.replaceAll(regex, "\\");

System.out.println(myEscapedString);

This will output:

这将输出:

ABC\^ \" \~ \* \? \:DEF