Validate text with regex

1

I have the following code:

final String msgRegex = "Produto [a-Z0-9À-ú, ]*";
        final String msg = "Produto Soja";
        if (msg.equals(msgRegex)) {
            System.out.println("Verdadeiro");
        } else {
            System.out.println("Falso");
        }

In this case it is as if it disregards the regex that is in msgRegex. How do I validate it by returning true in equals?

    
asked by anonymous 26.03.2018 / 15:10

1 answer

5

Your regex has an error that does not allow you to compile it, which is the range a-Z , correcting this error, the correct would be to use Pattern and Matcher , and check if there is any match between the default and the string with method find() :

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public classe RegexTest {

    public static void main (String[] args) {

        final String msgRegex = "Produto [a-z0-9À-ú, ]*";
        final String msg = "Produto Soja";

        Pattern r = Pattern.compile(msgRegex);
        Matcher m = r.matcher(msg);

        if(m.find()) {
             System.out.println("Verdadeiro");
        }else {
             System.out.println("Falso");
        }
    }
}

Running on ideone: link

Here are some related issues worth reading about using the Matcher class:

26.03.2018 / 15:17