-2

If I want to check whether a String contains "CVR", "CPR" and "NR". How do I do so? I tried with following method but got some issues

String testString = "cpr1210";

if (testString.contains("cpr||cvr||nr")) {
    System.out.println("yes");
}
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
JokesOnYou
  • 23
  • 6

3 Answers3

1

I might use String#matches() here, with a regex alternation:

String input = "cpr1210";
if (input.matches("(?i).*(?:cpr|cvr|nr).*")) {
    System.out.println("MATCH");
}

If you really wanted to use String#contains(), then you would need to have three separate calls to that method, for each sequence.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

As mentioned in my comment to your question, you may use String#contains().

    String testString = "cor1210";
    // will not print yes, because none of the sequences fit
    if (testString.contains("cpr") || testString.contains("cvr") || testString.contains("nr")) {
        System.out.println("yes");
    }

Make sure your logic-syntax in the if-clause is correct.

maloomeister
  • 2,461
  • 1
  • 12
  • 21
0

You can check whether a String contains another String (a substring) with the String.contains() method. It returns a boolean value. Keep in mind that this method is case sensitive. If you want to do case-insensitive search then use the same technique, convert both input and search string in same case and then call the method.

    String testString = "cor1210";

    //checks whether testString contains CVR, CPR or NR
    if (testString.contains("CVR")||testString.contains("CPR")||testString.contains("NR")){
        System.out.println("yes");
    }
padjal
  • 1
  • 1