diff --git a/nop-commons/src/main/java/io/nop/commons/text/regex/IRegex.java b/nop-commons/src/main/java/io/nop/commons/text/regex/IRegex.java index 01677e1ae..f70d6e419 100644 --- a/nop-commons/src/main/java/io/nop/commons/text/regex/IRegex.java +++ b/nop-commons/src/main/java/io/nop/commons/text/regex/IRegex.java @@ -17,4 +17,6 @@ default boolean find(String text){ } List exec(String text); + + List match(String text); } diff --git a/nop-commons/src/main/java/io/nop/commons/text/regex/impl/JdkRegex.java b/nop-commons/src/main/java/io/nop/commons/text/regex/impl/JdkRegex.java index 4c9fe29a2..d12bc0a45 100644 --- a/nop-commons/src/main/java/io/nop/commons/text/regex/impl/JdkRegex.java +++ b/nop-commons/src/main/java/io/nop/commons/text/regex/impl/JdkRegex.java @@ -45,4 +45,17 @@ public List exec(String text) { return null; } } -} \ No newline at end of file + + @Override + public List match(String text) { + if (StringHelper.isEmpty(text)) + return null; + + Matcher matcher = pattern.matcher(text); + List ret = new ArrayList<>(); + while (matcher.find()) { + ret.add(matcher.group()); + } + return ret.isEmpty() ? null : ret; + } +} diff --git a/nop-commons/src/test/java/io/nop/commons/text/TestRegex.java b/nop-commons/src/test/java/io/nop/commons/text/TestRegex.java index 8abd3e546..39228fbae 100644 --- a/nop-commons/src/test/java/io/nop/commons/text/TestRegex.java +++ b/nop-commons/src/test/java/io/nop/commons/text/TestRegex.java @@ -17,6 +17,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNull; public class TestRegex { @Test @@ -69,4 +70,24 @@ public void checkIRegex() { String simpleName = list.get(1); assertEquals("SimpleDomainServiceDto", simpleName); } + + @Test + public void checkIRegexMatch() { + String input = "xxxxAA10002 BB10022 abcdefAA10003saasdsd"; + // 正则表达式, 提取匹配的字符串 + String regexString = "(AA\\d{4,}|BB\\d{4,})"; + IRegex regex = RegexHelper.compileRegex(regexString); + + List list = regex.match(input); + assertEquals(3, list.size()); + assertEquals("AA10002", list.get(0)); + assertEquals("BB10022", list.get(1)); + assertEquals("AA10003", list.get(2)); + + // 正则表达式, 不匹配应该返回 null + String regexString2 = "(CC.*)"; + IRegex regex2 = RegexHelper.compileRegex(regexString2); + List list2 = regex2.match(input); + assertNull(list2); + } }