Search code examples
javaseleniumassert

How to match the patterns in java with assert J for below string


I have a string like this

String xyz ="JAVAxxxxxxxxxxxxxx   ID: 123678   VERSION: 3"

and I want to know how I can verify that it conforms to aspecific pattern.

I do the assertion like this

assertThat(xyz).containsPattern("[A-Za-z]* ID: [0-9]* VERSION: [0-9]* ");

Solution

  • To build on the answer of stevecross, note that the suggested expression is pretty lenient. For example, it will match this:

    String xyz =" ID: VERSION: "
    

    You can be more strict in your matching if needed. Say, if you need to ensure non-blank words, use + instead of * like this:

    assertThat(xyz).matches("[A-Za-z]+ +ID: [0-9]+ +VERSION: [0-9]+");
    

    And if you need to have exactly three spaces between the key-value pairs, then add {3} to a class of characters including only space ([ ]), like this:

    assertThat(xyz).matches("[A-Za-z]*[ ]{3}ID: [0-9]*[ ]{3}VERSION: [0-9]*");
    

    I find online regex evaluators helpful. See for example this one: https://regex101.com/