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



我一直试图从字符串中找到一个特定的字母,但遇到了错误。我有一个数组,其中存储了大约1000个字符串,对于每个字符串,我都想找到第一个整数、第二个整数、特定的字母和一个实际的单词。例如,一个存储的字符串可以是:;1-36g:鳄梨酱";,其中我想返回值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

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

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

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

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

来源:https://regex101.com/

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);
}               
}

与其找一个可以匹配整条线的。同时检查CCD_ 2和。CCD_ 3,否则匹配器的组无效。

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

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

最新更新