简体   繁体   中英

Java regex special character in returned string

I'm mostly coding in Perl and struggle now with a regex in 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 (+). 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.

Beware of null s.

您可以使用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 :

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  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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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