简体   繁体   中英

Escaping string within a Java application that would be used for regex matching in Ruby

I am trying to escape a string within my Java application that would be used for regex matching in a Ruby script

I tried to use Pattern.quote(s) in Java but it appears that only add a prefix of \\Q and a suffix of \\E .

For example, this is the string that I want to escaped from my Java application and would be used for my Ruby script.

export PATH=/usr/local/eclipse:${JAVA_HOME}/bin:${PATH}

I guess I can always use String.replace("/","\\\\/") , String.replace("$", "\\\\$") and etc but it would be nice if there's an easier way to do that.

Since Java doesn't have much knowledge of Ruby regexp's, I'd venture this would be much easier and convenient to do in Ruby.

string_from_java = 'export PATH=/usr/local/eclipse:${JAVA_HOME}/bin:${PATH}'
escaped_string = Regexp.escape(string_from_java)
pattern = /someprefix#{escaped_string}somesuffix/

Yeah, it's always bugged me that they chose that approach over backslash-escaping. Here's what I use:.

public static String quotemeta(String str)
{
  if (str == null)
  {
    throw new IllegalArgumentException("String cannot be null");
  }

  int len = str.length();
  if (len == 0)
  {
    return "";
  }

  StringBuffer sb = new StringBuffer(len * 2);
  for (int i = 0; i < len; i++)
  {
    char c = str.charAt(i);
    if ("\\[](){}.*+?$^|#/".indexOf(c) != -1)
    {
      sb.append("\\");
    }
    sb.append(c);
  }
  return sb.toString();
}

I'm reasonably certain this will produce Ruby-safe strings. I did have portability in mind when I wrote it. That's why it escapes all bracket characters (opening and closing) except angle brackets as well as the hash symbol ( # ) and the forward slash ( / ).

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