首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >检查字符串是否包含特定单词后面的数字

检查字符串是否包含特定单词后面的数字
EN

Stack Overflow用户
提问于 2022-07-15 07:48:38
回答 2查看 133关注 0票数 -2

有人能帮我做字符串验证吗?我试图找到解决办法,但没有人满意。我有一只狗/猫/房子,1/老鼠/鸟,1/兔子。

我需要检查单词(用逗号)后是否有鸟,是否有数字。在我的情况下,有时我收到uri与数字:“鸟,1”,有时与字:“鸟,福”。谢谢你的建议。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-07-15 07:59:27

正如@Federico klez Culloca@The fourth bird建议的那样,您可以使用正则表达式(正则表达式,\\bbird,(?:[1-9]|1[0-9]|20)\\b),但是一些安全扫描不喜欢正则表达式。在任何情况下,其他(纯Java)解决方案将是:

在用户添加了更多条件后更新了答案。

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

代码语言:javascript
复制
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;
}

注意:我个人讨厌这些冗长的解决方案,我更喜欢1行REGEX。尽量避免使用regex。我避免regex的唯一情况是当它成为性能瓶颈和/或引起安全问题时。

票数 2
EN

Stack Overflow用户

发布于 2022-07-15 08:52:29

这是一个实用的算法,可以指定关键字!前提是包含参数的有效性与您的描述一致。

关键字,(允许空格)123/

代码语言:javascript
复制
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;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72990694

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档