Validate a text with regex

Asked

Viewed 163 times

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’s as if he disregarded the regex that is in msgRegex. How do I validate it by returning true in equals?

1 answer

4


Your regex has a little error that doesn’t 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 a match between the pattern and the string with the 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");
        }
    }
}

Functioning in the ideone: https://ideone.com/CS9vL8


Here are some related questions worth reading regarding class use Matcher:

  • Show, thank you very much.

Browser other questions tagged

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