Skip to content

Commit

Permalink
!108 新增正则表达式 match 函数,返回匹配的数组
Browse files Browse the repository at this point in the history
* 新增正则表达式 match 函数,返回匹配的数组
  • Loading branch information
codering authored and entropy-cloud committed Jan 22, 2025
1 parent 4a16c09 commit 0fec237
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,6 @@ default boolean find(String text){
}

List<String> exec(String text);

List<String> match(String text);
}
Original file line number Diff line number Diff line change
Expand Up @@ -45,4 +45,17 @@ public List<String> exec(String text) {
return null;
}
}
}

@Override
public List<String> match(String text) {
if (StringHelper.isEmpty(text))
return null;

Matcher matcher = pattern.matcher(text);
List<String> ret = new ArrayList<>();
while (matcher.find()) {
ret.add(matcher.group());
}
return ret.isEmpty() ? null : ret;
}
}
21 changes: 21 additions & 0 deletions nop-commons/src/test/java/io/nop/commons/text/TestRegex.java
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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<String> 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<String> list2 = regex2.match(input);
assertNull(list2);
}
}

0 comments on commit 0fec237

Please sign in to comment.