Cyryl Łukeniuk Cyryl Łukeniuk - 1 year ago 70
Java Question

Storing string with unknown character

Lets say I have a word Tyre. In some countries spelling is different - Tire

Is it possible to store a string in Java so for example something like T y|i re and if I check, maybe with use of regexp, it would return


String compare = "Ty|ire";
String detail = "Tyre";
String detail2 = "Tire";
System.out.println(detail.equalsIgnoreCase(compare)) // prints "true"
System.out.println(detail2.equalsIgnoreCase(compare)) // also "true"

Answer Source

You are looking for a character class regex, String compare = "T[yi]re";. The [yi] construct matches either y or i. Add (?i) (an embedded Pattern.CASE_INSENSITIVE option) to match in a case insensitive way:

String compare = "(?i)T[yi]re";
String detail = "Tyre";
String detail2 = "Tire";
System.out.println(detail.matches(compare));  // prints "true"
System.out.println(detail2.matches(compare)); // also "true"

See the online Java demo

If you have to alternate multicharacter parts of a string, use alternation groups, (y|ies) or (?:y|ies).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download