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
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.