简体   繁体   English

返回字符串中的Java正则表达式特殊字符

[英]Java regex special character in returned string

I'm mostly coding in Perl and struggle now with a regex in Java. 我主要是用Perl编写代码,现在用Java的正则表达式进行挣扎。 I have this: 我有这个:

// String dbfPath = "/result_feature/Monocytes-CD14+_H3K4me3_ENCODE_UW_bwa_samse"
// rs.getString = "Monocytes-CD14+_H3K4me3_ENCODE_UW_bwa_samse"

if(! dbfPath.matches(".*" + rs.getString("rs_name") + "/*"))

My problem is that the rs_name contains wildcards (+). 我的问题是rs_name包含通配符(+)。 I tried putting [] around, but then I have an illegal range (-). 我尝试将[]放在周围,但随后出现了非法范围(-)。

How can I avoid the returning string being interpreted? 如何避免返回的字符串被解释?

Thanks! 谢谢!

Use Pattern.quote(rs.getString("rs_name")) to automatically escape control characters. 使用Pattern.quote(rs.getString("rs_name"))自动转义控制字符。

Beware of null s. 当心null

您可以使用java.util.regex.Pattern.qoute()

if(! dbfPath.matches(".*" + java.util.regex.Pattern.qoute(rs.getString("rs_name") ) + "/*"))

Wrap your rs.getString() inside a Pattern.quote : rs.getString()包装在Pattern.quote

Pattern.quote(rs.getString("rs_name"))

Returns a literal pattern String for the specified String. 返回指定字符串的文字模式字符串。

You could add '\\Q' & '\\E' in your string direclty. 您可以在字符串内容中添加“ \\ Q”和“ \\ E”。

\Q  Nothing, but quotes all characters until \E
\E  Nothing, but ends quoting started by \Q





if(! dbfPath.matches(".*\\Q" + rs.getString("rs_name") + "\\E/*"))

One thing, you should make sure your string doesn't contain '\\E', if yes, the safe way is using Pattern.quote() methods. 一件事,您应该确保您的字符串不包含“ \\ E”,如果是,安全的方法是使用Pattern.quote()方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM