【问题标题】:Find the index of first integer inside a string in order to cut this string查找字符串中第一个整数的索引以剪切该字符串
【发布时间】:2017-12-31 11:43:51
【问题描述】:

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

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

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

【问题讨论】:

  • “我尝试了不同的解决方案” - 添加它们
  • 玩家信息字符串是否总是包含[...]
  • 如果保证元素被恰好两个空格分割,那么你可以直接被它们分割:currentPlayerInfo.split(" {2}")
  • @Aominè 不,并非总是如此
  • @azro 谢谢你,我会记住的

标签: java string indexing


【解决方案1】:

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

这将跳过字符串开头的所有数字和空格,并将所有内容最多包含多个空格,后跟一个数字。

这仅在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;
}

【讨论】:

    【解决方案2】:

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

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

    输出

    Dame Zeraphine [TBC]
    

    【讨论】:

      猜你喜欢
      • 2023-03-14
      • 2011-05-29
      • 2017-02-23
      • 2013-07-08
      • 2020-02-14
      • 1970-01-01
      • 2018-01-19
      • 2020-08-02
      • 1970-01-01
      相关资源
      最近更新 更多