BAEL-6816-create-stream-regex-matches (#14731)

* BAEL-6816-create-stream-regex-matches

* add unit test

---------

Co-authored-by: tienvn <tienvn@>
This commit is contained in:
vunamtien 2023-09-13 02:58:56 +07:00 committed by GitHub
parent 42188fdc2d
commit 9bec8ebcdb
2 changed files with 43 additions and 0 deletions

View File

@ -0,0 +1,16 @@
package com.baeldung.streams.regexmatches;
import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
public class StreamFromRegexUtil {
public static Stream<String> getStream(String input, String regex) {
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
return matcher.results().map(MatchResult::group);
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.streams.regexmatches;
import org.junit.Test;
import java.util.List;
import java.util.stream.Collectors;
import static java.util.Arrays.asList;
import static org.junit.Assert.assertEquals;
public class StreamFromRegexUnitTest {
@Test
public void whenInputStringIncludeLettersAndNumbersAndRegex_ThenReturnStreamOfNumbers() {
List<String> result = StreamFromRegexUtil.getStream("There are 3 apples and 2 bananas on the table.", "\\d+")
.collect(Collectors.toList());
assertEquals(asList("3", "2"), result);
}
@Test
public void whenInputStringsAndRegex_ThenReturnStreamOfJavaWords() {
List<String> result = StreamFromRegexUtil.getStream("sample sentence with some words Java Java", "\\bJava\\b")
.collect(Collectors.toList());
assertEquals(asList("Java", "Java"), result);
}
}