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

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


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/


I think the method you are looking for is matches(). Additionally your regex does not match the given string. The string contains multiple spaces between the 'blocks'. Thus you need to specify that in the regex:

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