How to extract a substring using regex

前端 未结 14 1295
暖寄归人
暖寄归人 2020-11-22 13:37

I have a string that has two single quotes in it, the \' character. In between the single quotes is the data I want.

How can I write a regex to extract

14条回答
  •  逝去的感伤
    2020-11-22 14:28

    Since Java 9

    As of this version, you can use a new method Matcher::results with no args that is able to comfortably return Stream where MatchResult represents the result of a match operation and offers to read matched groups and more (this class is known since Java 1.5).

    String string = "Some string with 'the data I want' inside and 'another data I want'.";
    
    Pattern pattern = Pattern.compile("'(.*?)'");
    pattern.matcher(string)
           .results()                       // Stream
           .map(mr -> mr.group(1))          // Stream - the 1st group of each result
           .forEach(System.out::println);   // print them out (or process in other way...)
    

    The code snippet above results in:

    the data I want
    another data I want
    

    The biggest advantage is in the ease of usage when one or more results is available compared to the procedural if (matcher.find()) and while (matcher.find()) checks and processing.

提交回复
热议问题