【发布时间】: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