-3

This could be a dump question, I want to find exact string in case insensitive mode.

So suppose i have string "Test" and I found for "test", it should me return "Test".

I know that I can do that by simply converting to lower case and comparing, but I need regex solution only.

I have tried

    String test = "test";
    String patternString = "[\\$#@\\^&]" + test + "(\\s|$)";
    System.out.println("Test".matches(patternString));

It returns false though I am expecting true. I really don't know what above expression means that's why I am here.

EDIT

I know String.equalsIgnoreCase(another) method, but I told that I need it to do in regex way because I am using spring mongoDB environment so I can match regex into document directly using regex.

commit
  • 4,777
  • 15
  • 43
  • 70

2 Answers2

2

To compare two String ignoring case, you should use String.equalsIgnoreCase(another). Do not use regular expressions unless you really need to.

Tunaki
  • 132,869
  • 46
  • 340
  • 423
  • i think he was trying to do something with this `"[\\$#@\\^&]"` pattern – Avinash Raj Feb 20 '15 at 13:15
  • 2
    It sounds like he is explicitly saying he needs a regular expression... – David says Reinstate Monica Feb 20 '15 at 13:16
  • Avinash: true, but it seems he was not aware of the equalsIgnoreCase possibility, leading him to alter the Strings (to lowercase) and compare them. It is indeed plausible to assume it had to be a regex, but it is just as plausible he thought he needed a regex to compare them without changing the original values, which he doesn't. – Stultuske Feb 20 '15 at 13:19
  • @commit It is better you clarify what you meant because there's different solutions. – Bonga Mbombi Feb 20 '15 at 13:22
  • I explicitly said that I need it in regex way, I know equalsIgnoreCase method. – commit Feb 20 '15 at 13:30
1

You need to use a case insensitive modifier.

String patternString = "(?i)(?:^|[\\$#@\\^&])" + test + "(?:\\s|$)";

Add \\s inside the character class [...] if necessary.

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274