【问题标题】:Searching for a sequence in String which is a combination of constant+variable在字符串中搜索一个由常量+变量组合而成的序列
【发布时间】:2014-07-24 11:31:55
【问题描述】:

我有一个字符串 S = "AA AA BB :1 CC :2 DD :30 EE :149";

如何在字符串 S 上循环并 1 接 1 抓取以 : 开头的每个数字并将它们保存在 Int 中?

例如

 int holder;
    String S = "AA AA BB :1 CC :2 DD :30 EE :149";
    // Loop Start

    holder = s.Grab1stnumberstarting with :
    System.out.println(holder);

    // Loop End

这样我就得到了输出:

:1
:2
:30
:149

【问题讨论】:

  • 使用正则表达式?
  • 您可以使用正则表达式,正则表达式:\d+find()迭代搜索整数,见fiddle.re/h4m7b,使用String#SubString删除:,并将其解析为@987654328 @。尝试一下,如果有问题,请在此处提问!但请先尝试!

标签: java string stringbuilder


【解决方案1】:

试试正则表达式

public static void main(String[] args) {
    String s = "AA AA BB :1 CC :2 DD :30 EE :149";
    Pattern p = Pattern.compile(":\\d+");
    Matcher m = p.matcher(s);
    while (m.find()) {
        System.out.println(m.group());
    }

}

O/P:

:1
:2
:30
:149

【讨论】:

    【解决方案2】:

    您可以通过Positive Lookbehind 使用简单的正则表达式模式

    Live demo

    示例代码:

    String s = "AA AA BB :1 CC :2 DD :30 EE :149";
    
    Pattern p = Pattern.compile("(?<=:)\\d+");
    Matcher m = p.matcher(s);
    while (m.find()) {
        int number = m.group()
        System.out.println(":"+number);
    }
    

    正则表达式模式解释:

      (?<=                     look behind to see if there is
        :                        ':'
      )                        end of look-behind
      \d+                      digits (0-9) (1 or more times (most possible))
    

    【讨论】:

      【解决方案3】:

      为了补全,也为了避免现在有两个问题,不使用正则表达式就可以轻松实现:

      String s = "AA AA BB :1 CC :2 DD :30 EE :149";
      String[] parts = s.split(" ");
      for(String part : parts) {
          if(part.startsWith(":")) {
              System.out.println(part);
          }
      }
      

      这假定所需的输出是以 : 开头的任何内容,而不仅仅是数字,尽管可以很容易地提升为仅找到数字。

      【讨论】:

      • 并假设分隔符是" "(空格)。
      猜你喜欢
      • 1970-01-01
      • 2011-03-10
      • 2020-10-11
      • 2018-03-03
      • 2015-07-29
      • 1970-01-01
      • 1970-01-01
      • 2014-06-16
      • 1970-01-01
      相关资源
      最近更新 更多