Java 如何匹配首次出现的模式?

Java 如何匹配首次出现的模式?,java,matcher,Java,Matcher,如何始终获取与模式匹配的第一个元素 Pattern pattern = Pattern.compile("(\\d+)K"); Matcher matcher = pattern.matcher("CARRY8K"); baggageWeight = matcher.group(); //I'd like to extract the "8" 结果:java.lang.IllegalStateException:未找到匹配项 为什么?如果您这样做,请从字符串“CARRY8K”中提取“8” 我建

如何始终获取与模式匹配的第一个元素

Pattern pattern = Pattern.compile("(\\d+)K");
Matcher matcher = pattern.matcher("CARRY8K");
baggageWeight = matcher.group(); //I'd like to extract the "8"
结果:
java.lang.IllegalStateException:未找到匹配项


为什么?

如果您这样做,请从字符串“CARRY8K”中提取“8”


我建议使用String.indexOf(String)来查找字符串在主字符串中的位置。然后使用indexOf可以提取指定索引处的值。例如:

String s = "CARRY8K";
int index = s.indexOf("8");
“索引”将设置为指定字符的第一个实例的位置。在本例中,“8”。然后,您可以使用索引执行其他操作——打印字符的位置,或将其从主字符串中删除

如果要删除它,只需使用stringbuilder和setCharAt()方法:


这会将指定索引处的字符替换为空白,从而有效地将其从主字符串中删除。

matcher.group()。这里您没有使用
find()
,它尝试查找与模式匹配的输入序列的下一个子序列

“extract”是指从字符串中“remove”,还是要为其设置一个变量,或者什么?您没有说要提取未知数字。下次我建议你把问题弄清楚,这样更容易理解你在找什么。
String s = "CARRY8K";
int index = s.indexOf("8");
StringBuilder newString = new StringBuilder(s);
newString.setCharAt(index, '');