ReUtil类添加delLast方法✒️

This commit is contained in:
大火yzs 2021-05-04 14:55:39 +08:00
parent 4f634c384d
commit db42db25da
2 changed files with 81 additions and 15 deletions

View File

@ -299,6 +299,46 @@ public class ReUtil {
return pattern.matcher(content).replaceFirst(StrUtil.EMPTY); return pattern.matcher(content).replaceFirst(StrUtil.EMPTY);
} }
/**
* 删除匹配的最后一个内容
*
* @param regex 正则
* @param str 被匹配的内容
* @return 删除后剩余的内容
* @since 5.6.5
*/
public static String delLast(String regex, CharSequence str) {
if (StrUtil.hasBlank(regex, str)) {
return StrUtil.str(str);
}
final Pattern pattern = PatternPool.get(regex, Pattern.DOTALL);
return delLast(pattern, str);
}
/**
* 删除匹配的最后一个内容
*
* @param pattern 正则
* @param str 被匹配的内容
* @return 删除后剩余的内容
* @since 5.6.5
*/
public static String delLast(Pattern pattern, CharSequence str) {
if (null != pattern && StrUtil.isNotBlank(str)) {
String last = "";
for (Matcher matcher = pattern.matcher(str); matcher.find(); ) {
last = matcher.group();
}
if (StrUtil.isNotBlank(last)){
return StrUtil.subBefore(str, last, Boolean.TRUE) + StrUtil.subAfter(str, last, Boolean.TRUE);
}
}
return StrUtil.str(str);
}
/** /**
* 删除匹配的全部内容 * 删除匹配的全部内容
* *

View File

@ -1,6 +1,7 @@
package cn.hutool.core.util; package cn.hutool.core.util;
import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.PatternPool;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
@ -38,6 +39,31 @@ public class ReUtilTest {
Assert.assertEquals("ZZbbbccc中文1234", resultDelFirst); Assert.assertEquals("ZZbbbccc中文1234", resultDelFirst);
} }
@Test
public void delLastTest(){
String blank = "";
String word = "180公斤";
String sentence = "10.商品KLS100021型号xxl适合身高180体重130斤的用户";
//空字符串兼容
Assert.assertEquals(blank,ReUtil.delLast("\\d+", blank));
Assert.assertEquals(blank,ReUtil.delLast(PatternPool.NUMBERS, blank));
//去除数字
Assert.assertEquals("公斤",ReUtil.delLast("\\d+", word));
Assert.assertEquals("公斤",ReUtil.delLast(PatternPool.NUMBERS, word));
//去除汉字
Assert.assertEquals("180",ReUtil.delLast("[\u4E00-\u9FFF]+", word));
Assert.assertEquals("180",ReUtil.delLast(PatternPool.CHINESES, word));
//多个匹配删除最后一个 判断是否不在包含最后的数字
Assert.assertFalse(ReUtil.delLast("\\d+", sentence).contains("130"));
Assert.assertFalse(ReUtil.delLast(PatternPool.NUMBERS, sentence).contains("130"));
//多个匹配删除最后一个 判断是否不在包含最后的数字
Assert.assertFalse(ReUtil.delLast("[\u4E00-\u9FFF]+", sentence).contains("斤的用户"));
Assert.assertFalse(ReUtil.delLast(PatternPool.CHINESES, sentence).contains("斤的用户"));
}
@Test @Test
public void delAllTest() { public void delAllTest() {
// 删除所有匹配到的内容 // 删除所有匹配到的内容