繁体   English   中英

如何模式匹配首次出现?

[英]How to pattern match first occurence?

如何始终将第一个元素与模式匹配?

Pattern pattern = Pattern.compile("(\\d+)K");
Matcher matcher = pattern.matcher("CARRY8K");
baggageWeight = matcher.group(); //I'd like to extract the "8"

结果: java.lang.IllegalStateException: No match found

为什么?

matcher.group()抛出IllegalStateException如果尚未尝试匹配,或者上一个匹配操作失败。 这里你没有使用find()试图找到与模式匹配的输入序列的下一个子序列。

如果你喜欢这样,你从字符串“CARRY8K”中提取“8”

Pattern pattern = Pattern.compile("(\\d+)K");
Matcher matcher = pattern.matcher("CARRY8K");
if (matcher.find()) {
   System.out.println(matcher.group(1));
}

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

String s = "CARRY8K";
int index = s.indexOf("8");

“index”将设置为指定字符的第一个实例的位置。 在这种情况下,“8”。 然后,您可以使用索引执行其他操作 - 打印字符的位置,或从主字符串中删除它。

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

StringBuilder newString = new StringBuilder(s);
newString.setCharAt(index, '');

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM