how to compare two strings in java?

天涯浪子 提交于 2019-11-28 13:06:02

I'd try to "normalize" strings. Make both uppercase, replace "\s+X\s+" with "X", replace "\s+%" with "%", "\s+MG" with "MG" etc., then split it by whitespaces or some regex (Scanner class or Guava's Splitter) and compare parts of the string.

Based on your sample data, I advise normalizing every string by adding space between every group of digits and characaters. So sample 2

TASIGNA CAPS 1X200MG  <---->  TASIGNA CAPS 112 X 200 MG

would become:

TASIGNA CAPS 1 X 200 MG  <---->  TASIGNA CAPS 112 X 200 MG

Now just split on whitespace and compare the single groups. All should be the same, but one numerical group. Depending on the type of your data (CAPS, COMP, CREME, ...) you may ignore another group. Either the one before the X, or the one after CREME, etc. This strongly depends on your data.

After Sean owen's suggestion; probably following Regex can be used:

/(\w.*?)(\d+)X(\w.*)/

and capture group 1 and 3 should be equal after dropping any space in-between.


  1. Spilt the strings by space .

  2. Compare [0] and [1] of splitted results.

  3. Combine all remaining indexes to make a single string. (use trim before combining)

  4. find indexOf X and use subString till end of string.

  5. Use equals OR equalsIgnoreCase to compare the combined (sub)strings.

  6. Repeat from step 1, for each set of strings.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!