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 01677e1ae20a3814c6c549b5ff0d2db9a8f26754..f70d6e419f74c6189fdbb7531858eccd00b10958 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 @@ public interface IRegex { } 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 4c9fe29a29f0652789f8180ede381248ab137d21..d12bc0a45315e2dfaf853ecf9715f2ec67daf8bf 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 class JdkRegex implements IRegex { 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 8abd3e54601892ca990157b51edced96cd4768ea..39228fbae0d90e90f1e7ef770dc11d38436acff1 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 java.util.regex.Pattern; 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 class TestRegex { 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); + } }