找到字符串中第一个整数的索引以剪切此字符串



我目前遇到了一个烦人的问题。我想找到字符串中第一个整数值的索引,以便接下来切割字符串。

String currentPlayerInfo = "97  Dame Zeraphine [TBC]    10  41.458  481 363 117";
String currentPlayerName = "Dame Zeraphine [TBC]"; // This ís a kind of output i would like to get from the string above

我尝试了不同的解决方案,但最终无法找到合适的解决方案。如果我能得到一些帮助,我会很高兴。

如果你愿意使用正则表达式,你可以使用模式^[ds]+(.*?)s+d

这将跳过 String 开头的所有数字和空格,并将所有内容最多占用多个空格,后跟一个数字。

仅当playerName不包含数字(前面有空格(时,这才有效。

String currentPlayerInfo = "97  Dame Zeraphine [TBC]    10  41.458  481 363 117";
Pattern pattern = Pattern.compile("^[\d\s]+(.*?)\s+\d");
Matcher matcher = pattern.matcher(currentPlayerInfo);
String currentPlayerName;
if (matcher.find()) {
    currentPlayerName = matcher.group(1);
} else {
    currentPlayerName = null;
}

您可以替换输入中的所有数字以获得该结果,因此您可以将 replaceAll 与此正则表达式d+(.d+)?一起使用:

currentPlayerInfo = currentPlayerInfo.replaceAll("\d+(\.\d+)?", "").trim();

输出

Dame Zeraphine [TBC]

最新更新