【问题标题】:Finding specific letter in string - Not working (Java)在字符串中查找特定字母 - 不工作(Java)
【发布时间】:2021-03-28 15:22:10
【问题描述】:

我一直在尝试从字符串中查找特定字母,但出现错误。我有一个存储了大约 1000 个字符串的数组,对于每个字符串,我想找到第一个整数、第二个整数、特定字母和一个实际单词。例如,一个存储的字符串可能是:“1-36 g: guacamole”,我想在其中返回值 1、36、字母 g 和单词 guacamole。到目前为止,我已经找到了获取前两个数字的方法,但不是字符串。有没有办法从它们的索引或它们与分隔符的相对位置中查找它们?这是我目前的代码:

for (int x = 0; x < list.length; x++) { // For each stored string, check...
                    
    current = list[x]; // First, set current variable to current word from array
                    
    Matcher first = Pattern.compile("\\d+").matcher(current);
    first.find();
    min = Integer.valueOf(first.group()); // Get minimum value (from example, 1)

    first.find();
    max = Integer.valueOf(first.group()); // Get maximum value (from example, 36)
                    
    first.find();
    letter = String.valueOf(first.group()); // What I am trying to do to get first letter (from example, g)
                    
    System.out.println("Minimum value: " + min + " | Maximum value: " + max + " | Letter: " + letter);
                    
}

控制台中出现的只是以下错误:Exception in thread "main" java.lang.IllegalStateException: No match found

我还没有得到任何代码来找到这个词,我接下来会尝试。如果有人也可以帮助我,那就太好了!

或者,如果您可以推荐另一种从每个字符串中查找这些值的方法,那也将不胜感激。如果我应该提供任何其他代码,请告诉我。提前致谢!

【问题讨论】:

  • 你为什么不一次捕获所有?说,"(\\d+)-(\\d+)\\s*(\\p{Alpha}+)\\s*:\\s*(.*)"?见ideone.com/JSUrUZ

标签: java arrays regex string


【解决方案1】:
Pattern recordPattern = Pattern.compile(".*(\\d+).*(\\d+) (.)\\: (.*)$").matcher(current);
for (String record : list) { // For each stored string, check...
    Matcher m = recordPattern.matcher(current);
    if (m.matches()) {
        int min = Integer.parseInt(m.group(1));
        int max = Integer.parseInt(m.group(2)); 
        String letter = m.group(2);
        String name = m.group(3);
                    
        System.out.printf("Minimum: %d | Maximum: %d | Letter: %s | Name: %s.%n",
              min, max, letter, name);
    }               
}

而不是 find one 可以匹配整行。始终检查find 的结果。 match 否则匹配器的组无效。

为了使代码更具可读性,在使用前声明变量。循环没有惩罚(调用堆栈上只有一个变量槽)。 (我知道在早期的 CS 中,在顶部声明所有变量被认为是一种很好的风格。)

错误是正则表达式 "\\d+",它代表 1 个或多个 digits。 Pattern 类的 javadoc

【讨论】:

    【解决方案2】:

    我只是在 regex101 上运行它,尝试从 1-36 g 匹配:鳄梨酱 这对我有用

    (\d).(\d+).(.*)\s(\w+)
    

    来源:https://regex101.com/

    【讨论】:

      猜你喜欢
      • 2017-09-25
      • 1970-01-01
      • 2013-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-06
      相关资源
      最近更新 更多