Regular Expression

2

I have an application that reads a string and needs to detect parameters contained in the string. The parameter has the following pattern <<<.texto>>> ( < and > are part of the parameter).

I was able to make an expression to capture the correct parameters. But it is also necessary to identify the incorrect parameters (errors caused when typing by the user). Eg: <texto>>> , <<Texto>>> , Texto>>>> and so on.

Expression for the correct parameters: (\<{3}(\w+)\>{3})+

Can anyone help me?

    
asked by anonymous 12.11.2015 / 19:32

1 answer

4

You can do this as follows:

public class Validator {

  public static boolean validarTexto(String texto) {
     Pattern p = Pattern.compile("\<{3}(\w+)\>{3}");
     Matcher retorno = p.matcher(texto);
     return retorno.matches();
  }

}

Test:

    System.out.println(Validator.validarTexto("<<<texto"));//false
    System.out.println(Validator.validarTexto("<<<texto2>>>"));//true
    System.out.println(Validator.validarTexto("<<<1texto>>"));//false
    System.out.println(Validator.validarTexto("<<<3texto2>>>"));//true

Test with if:

String seuTexto = "<<<texto";

if (Validator.validarTexto(seuTexto)) {
  System.out.println("Texto correto.");
} else {
  System.out.println("Texto inválido.");
}
    
12.11.2015 / 20:29