How to escape all metacharacters using Pattern.Compile(.)?

Asked

Viewed 140 times

3

Filing cabinet:

ftp://paginaqualquer.html

https://othersine.net/

http://mydeletina.php?id=

My code:

public static void main(String[] args){
     //Supondo que o readLine() esteja no loop != null
     String arquivoLinha = arquivo.readLine();
     Pattern padrao = Pattern.compile(arquivoLinha); //O problema está aqui
     Matcher texto = padrao.matcher("http://minhapagina.php?id=");
     while (texto.find()){
          System.out.println(texto.group());
     }
}

When the last line arrives at the fileLine variable(http://mydeletina.php?id), It happens what I didn’t want to happen: The metacharacter "?" has power, thus modifying my research. I could even use the exhaust pipe " " to ignore the "?" but how do I do that? Or at least ignore any metacharacter that is in the fileLine variable and consider it as literal.

I tried to do so:

Pattern.compile("["+"("+arquivoLinha+")"+"]");

Using the line inside the group, that inside the list to ignore the metacharacters, only that it’s not working very well.

1 answer

4


You need the compiled standard to be literal, that is, that meta characters or escape characters in the pattern do not have regular expression treatment.

To do this simply compile the pattern by informing a flag saying this, that "escape" such characters. You find this flag on its own Pattern, to LITERAL.

To compile the pattern using this flag just do this:

final Pattern padrao = Pattern.compile("http://minhapagina.php?id=", Pattern.LITERAL);
final Matcher texto = padrao.matcher("http://minhapagina.php?id=");
while (texto.find()) {
    System.out.println(texto.group());
}

This will make your pattern "case" as text, then this will be printed:

http://minhapagina.php?id=

Browser other questions tagged

You are not signed in. Login or sign up in order to post.