当前位置: 动力学知识库 > 问答 > 编程问答 >

regex - 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?

网友答案:
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-3: As Sebastian Proske and Boris the Spider commented and unlike what a tutorial led me to believe, String.matches does match the regular expression as if it had anchors (as if it already started with a ^ and ended with a $) so those are not required. That will teach me to read tutorials and not double check. ^^

分享给朋友:
您可能感兴趣的文章:
随机阅读: