Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/399.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在字符串中查找特定字母-不工作(Java)_Java_Arrays_Regex_String - Fatal编程技术网

在字符串中查找特定字母-不工作(Java)

在字符串中查找特定字母-不工作(Java),java,arrays,regex,string,Java,Arrays,Regex,String,我一直试图从字符串中找到一个特定的字母,但出现了错误。我有一个存储了大约1000个字符串的数组,对于每个字符串,我想找到第一个整数、第二个整数、特定字母和一个实际单词。例如,一个存储的字符串可以是:“1-36 g:guacamole”,其中我希望返回值1、36、字母g和单词guacamole。到目前为止,我已经找到了获取前两个数字的方法,但不是字符串。有没有办法从它们的索引或它们与分隔符的相对位置查找它们?这是我目前的代码: for (int x = 0; x < list.length;

我一直试图从字符串中找到一个特定的字母,但出现了错误。我有一个存储了大约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);
                    
}
对于(int x=0;x
控制台中出现的所有错误如下:
线程“main”java.lang.IllegalStateException中的异常:未找到匹配项

我还没有找到这个单词的代码,我将在下一步尝试。如果有人也能帮我,那就太好了


或者,如果您可以推荐另一种方法从每个字符串中查找这些值,也将非常感谢。如果我需要提供任何其他代码,请让我知道。提前谢谢

我刚刚在regex101上运行了这个,试图匹配1-36克:鳄梨酱 这对我有用

(\d).(\d+).(.*)\s(\w+)
资料来源:

而不是找到一个可以匹配整行。始终检查
find
resp的结果<代码>匹配
,否则匹配者的组无效

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


错误是regex
“\\d+”
,它代表一个或多个digit。类的javadoc

为什么不一次捕获所有内容?比如说,用
“(\\d+)-(\\d+)\\s*(\\p{Alpha}+)\\s*:\\s*(*)”
?看见
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);
    }               
}