Search code examples
javamessageformat

Check if a String matches a particular MessageFormat in Java?


I have a MessageFormat like so;

final MessageFormat messageFormat = new MessageFormat("This is token one {0}, and token two {1}");

I'm just wondering if I have some Strings like;

String shouldMatch = "This is token one bla, and token two bla";
String wontMatch = "This wont match the above MessageFormat";

How do I check if the above Strings were created using messageFormat? I.e. that they match the messageFormat?

Many thanks!


Solution

  • You can do that using Regular Expressions and Pattern and Matcher classes. A simple example:

    Pattern pat = Pattern.compile("^This is token one \\w+, and token two \\w+$");
    Matcher mat = pat.matcher(shouldMatch);
    if(mat.matches()) {
       ...
    }
    

    Explanation of regex:

    ^ = beginning of line
    \w = a word character. I put \\w because it is inside a Java String so \\ is actually a \
    + = the previous character can occur one ore more times, so at least one character should be there
    $ = end of line
    

    If you want to capture the tokens, use braces like this:

    Pattern pat = Pattern.compile("^This is token one (\\w+), and token two (\\w+)$");
    

    You can retrieve the groups using mat.group(1) and mat.group(2).