【问题标题】:Java equivalent of JavaScript's String.match()Java 等效于 JavaScript 的 String.match()
【发布时间】:2010-11-29 18:02:42
【问题描述】:

JavaScript 的 String.match() 的 Java 等价物是什么

我需要获取一个数组或所有匹配项的列表

例子:

var str = 'The quick brown fox jumps over the lazy dog';
console.log(str.match(/e/gim));

给予

["e", "e", "e"]

http://www.w3schools.com/jsref/jsref_match.asp

【问题讨论】:

    标签: java javascript regex


    【解决方案1】:

    查看Regex tutorial

    您的代码应该类似于以下内容:

    String input = "The quick brown fox jumps over the lazy dog";
    Matcher matcher = Pattern.compile("e").matcher(input);
    
    while ( matcher.find() ) {
        // Do something with the matched text
        System.out.println(matcher.group(0));
    }
    

    【讨论】:

      【解决方案2】:

      查看regex 包中的PatternMatcher 类。特别是Matcher.find 方法。这不会返回数组,但您可以在循环中使用它来遍历所有匹配项。

      【讨论】:

        【解决方案3】:

        String.matches(String regex) 是更直接的等价物,但仅用于一次性正则表达式。如果您要多次使用它,请按照建议使用Pattern.compile

        【讨论】:

          猜你喜欢
          • 2011-06-23
          • 1970-01-01
          • 1970-01-01
          • 2018-05-30
          • 2016-05-10
          • 1970-01-01
          • 2012-08-19
          • 2023-03-21
          • 1970-01-01
          相关资源
          最近更新 更多