fatherazrael fatherazrael - 1 year ago 44
Java Question

How to do String comparison of look alike words, using Regular expressions in Java?

I have two String

String x = "DMXX"; //or DMYY or DMZZ

I want to check equality.

Earlier i was doing it like

if(x.equals("DMXX") || x.equals("DMYY") || x.equals("DMZZ")){
//Do this and that

Instead of three different statements; i want to do it in one.

In above string 'DM' will be common for all; only change will be XX/YY/ZZ.

What will be syntax for regular expressions to make it one statement instead of two?

Also, additional query: Do Guava or Apache Commons have some functionality to achieve same?

Answer Source
if (x.matches("^DM(?:XX|YY|ZZ)$") {
    // Do whatever

Edit 1: You can of course change the characters DM, XX, YY and ZZ to whatever you need and note that XX and friends do not have to be the same length. For instance with DM1234 and DM2, the regex "^DM(?:1234|2|ZZ)$" will work just fine.

Edit 2: I just realized you asked for equality, so I refined the regex because if you match "DM(?:XX|YY|ZZ)" it will match AnythingDMXX and DMXXAnything so if you're testing equality, you should use ^ and $ to mark the start and the end of the string respectively.