【问题标题】:What regex should i use for this split?我应该为这个拆分使用什么正则表达式?
【发布时间】:2021-04-16 19:23:11
【问题描述】:

我有这个字符串:

" < 2, 3, 4 >"

我想拆分以便拥有这样的数组:

["2", "3", "4"]

提前致谢。

【问题讨论】:

  • String[] arr = new Scanner(" &lt; 2, 3, 4 &gt;").useDelimiter("[&lt;, &gt;]+").tokens().toArray(String[]::new); System.out.println(Arrays.toString(arr));
  • 匹配&lt;\s*(\d+(?:\s*\,\s*\d+)*)\s*&gt;,在$1上进行拆分\s*,\s*

标签: java regex split


【解决方案1】:
string.replaceAll("(\\s|\\<|\\>)", "").split(",");

使用发布字符串的输出是:["2", "3", "4"]

【讨论】:

    【解决方案2】:
    \s([0-9]+)(,?)
    
    • '\s' 匹配空格
    • '[0-9]' 表示数字
    • “+”表示一个或多个

    所以你正在匹配:(任何空格)(至少一个数字)(可选的逗号)

    【讨论】:

      【解决方案3】:

      String[]Part=strSource.split(",");
      Int[]arrInt= new Int[Part.length()]
      For(into i=0;i {
      arrInt[i]=Integer.parseInt(Part[i]);
      }

      我猜这样的代码可以解决问题。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-07-16
        • 2010-12-10
        • 2012-09-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-18
        • 1970-01-01
        相关资源
        最近更新 更多