Home > Enterprise >  Check if string contains number after specific word
Check if string contains number after specific word

Time:07-15

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.

CodePudding user response:

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 when it becomes performance bottleneck and/or causes a security concern.

CodePudding user response:

This is a practical algorithm, you can specify the keyword! The premise is that the validity of the contains parameter is in line with your description.

keyword, (spaces are allowed)123/

public static void main(String[] args) throws IOException {
    String contains = "/dog/cat/house,1/mouse/bird,a/rabbit";
    FreeTest f = new FreeTest();
    boolean has = f.hasNumber(contains, "bird");
    System.out.println(has);
}

/**
 * Check if string contains number after specific word
 *
 * @param contains string contains
 * @param key      the specific word (without comma)
 * @return yes or not
 */
public boolean hasNumber(String contains, String key) {
    int commaIndex = contains.indexOf(',', contains.indexOf(key));
    int startIndex = commaIndex   1;
    boolean hasNumber = true;
    while (true) {
        char c = contains.charAt(startIndex  );
        if (c == '/') break; // exit
        if (c != ' ') {
            hasNumber = Character.isDigit(c);
        }
    }
    return hasNumber;
}
  • Related