Skip to content
Advertisement

Check if string contains number after specific word [closed]

can someone help me with string validation? I tried to find the solution, but none was satisfied. I have the uri e.g. /dog/cat/house,1/mouse/bird,1/rabbit.

I need to check if after word (with comma) bird, there is a number or not. In my case sometimes i receive uri with number: “bird,1” and sometimes with word: “bird,foo”. Thank you for any suggestions.

Advertisement

Answer

As @Federico klez Culloca and @The fourth bird suggested you could use a regular expression (\bbird,(?:[1-9]|1[0-9]|20)\b) but some security scans don’t like regular expressions. In any case, one another (pure Java) solution would be:

Updated the answer after user added more conditions.

would look for range 1, 2 .. 20 (01, 02 would return false).

public static boolean isNumber() {
    // you can parametrize these 2
  String input = "/dog/cat/house,1/mouse/bird,10/rabbit.";
  String strOfInterest = "/bird,";

  boolean isStringEndingInLT20 = false;
  int indxOfInterest = input.indexOf("/bird,") + strOfInterest.length();
  char c1 = input.charAt(indxOfInterest);
  char c2 = input.charAt(indxOfInterest + 1);
  int i1 = Character.getNumericValue(input.charAt(indxOfInterest));

  if (Character.isDigit(c1) && Character.isDigit(c2)) {
    int num = Integer.parseInt("" + c1 + c2);
    if ((i1 > 0) && (num >= 1) && (i1 <= 20)) isStringEndingInLT20 = true;
  } else if (Character.isDigit(c1)) {
    if ((i1 >= 1) && (i1 <= 9)) isStringEndingInLT20 = true;
  }
  return isStringEndingInLT20;
}

NOTE: I personally hate these verbose solutions and would prefer 1 line REGEX. Try to avoid it and use regex. The only times I avoid regex is when it becomes performance bottleneck and/or causes a security concern.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement