【问题标题】:Java Matching multiple tokens with RegexJava使用正则表达式匹配多个标记
【发布时间】:2012-08-02 11:28:05
【问题描述】:

我发现一个正则表达式匹配用 {} 包围的标记,但它似乎只找到第一个找到的项目。

如何更改以下代码以便找到所有标记而不仅仅是 {World},我需要使用循环吗?

// The search string
String str = "Hello {World} this {is} a {Tokens} test";

// The Regular expression (Finds {word} tokens)
Pattern pt = Pattern.compile("\\{([^}]*)\\}");

// Match the string with the pattern
Matcher m = pt.matcher(str);

// If results are found
if (m.find()) {
    System.out.println(m);
    System.out.println(m.groupCount()); // 1
    System.out.println(m.group(0)); // {World}
    System.out.println(m.group(1)); // World (Get without {})
}

【问题讨论】:

    标签: java regex token


    【解决方案1】:

    groupCount() 方法不返回匹配数,它返回此匹配器模式中的捕获组数。您在模式中定义了一个组,因此此方法返回 1。

    您可以通过再次调用find() 来找到与您的模式匹配的下一个匹配项;它将尝试找到与模式匹配的输入序列的下一个子序列。当它返回false 时,您将知道没有更多匹配项。

    因此,您应该像这样遍历匹配项:

    while (m.find()) {
        System.out.println(m.group(0));
    }
    

    【讨论】:

    • 我接受了 biziclop 的回答,因为它为我提供了我需要的解决方案,但感谢您的解释。这也很有用。
    【解决方案2】:

    是的,在您的代码中,您只需进行一次匹配,然后在该匹配中获取组。

    如果你想得到其他匹配,你必须在循环中继续匹配,直到find()返回false。

    所以基本上你只需要用while 替换if 就可以了。

    【讨论】:

    • 谢谢这很好用,只是想知道有没有简单的方法来获得匹配的总数?或者最好的方法是将while循环中找到的每个项目添加到一个总变量中?
    猜你喜欢
    • 2010-12-14
    • 1970-01-01
    • 1970-01-01
    • 2014-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多