1、獲取第一個匹配結果
public static String matchFirst(String regex, String source) {
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(source);
if (matcher.find()) {
return matcher.group().trim();
}
return StringUtils.EMPTY;
}
2、獲取第一個匹配結果的索引
public static Integer indexFirst(String regex, String source) {
String matchFirst = matchFirst(regex, source);
if (StringUtils.isNotBlank(matchFirst)) {
return source.indexOf(matchFirst);
} else {
return -1;
}
}
3、獲取所有匹配結果
public static List<String> matchList(String regex, String source) {
List<String> list = new ArrayList<>();
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(source);
while (matcher.find()) {
list.add(matcher.group().trim());
}
return list;
}
4、判斷是否有匹配項
public static Boolean match(String regex, String source) {
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(source);
return matcher.find();
}
5、通過正則來切割字串
public static List<String> splitList(String regex, String source) {
Pattern pattern = Pattern.compile(regex);
List<String> list = new ArrayList<>();
for (String item : Arrays.stream(pattern.split(source)).filter(StringUtils::isNotBlank).collect(Collectors.toList())) {
list.add(item.trim());
}
return list;
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結