java - Java 正则表达式表现怪异
问题描述
我有以下测试用例,
@Test
public void test_check_pattern_match_caseInSensitive_for_pre_sampling_filename() {
// given
String pattern = "Sample*.*Selection*.*Preliminary";
// when
// then
assertThat(Util.checkPatternMatchCaseInSensitive(pattern, "Sample selectiossn preliminary"), is(false));
assertThat(Util.checkPatternMatchCaseInSensitive(pattern, "sample selection preliminary"), is(true));
}
Util 方法是:
public static boolean checkPatternMatchCaseInSensitive(String pattern, String value) {
Pattern p = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
Matcher matcher = p.matcher(value);
if (matcher.find())
return true;
return false;
}
有人可以帮忙吗,为什么正则表达式Sample*.*Selection*.*Preliminary
匹配 fileName = Sample selectiossn preliminary
?
这个测试用例应该通过,但由于第一个断言而失败。:S
解决方案
in 正则表达式表示前一个字符的*
0 个或多个,而.
表示任何单个字符。
你的表达正在寻找的是:
- 确切地
Sampl
- 0个或更多
e
- 0 个或多个任意字符
- 确切地
Selectio
- 0个或更多
n
- 0个或更多任何字符等等
问题属于第 5 点和第 6 点:
在第 5 点下没有n
找到,ssn
与第 6 点匹配
推荐阅读
- sql - 检测列值是否包含在 SQL Server 中另一个表的列中的最佳方法
- java - 给定一个整数数组和一个总和,任务是查找是否存在给定数组的子集,其总和等于给定总和
- django - 我可以在 Django UniqueConstraint 中使用相关模型的字段吗?
- php - 如何更改 apache2 中的 REQUEST_URI?
- android - Xamarin Android ImageView 不显示
- python - 分类指标无法处理 accuracy_score 中连续目标和二元目标的混合
- sql-server - 如何搭建 DbContext 但忽略数据库中的表
- c++ - 程序意外结束
- javascript - JQuery/Javascript - 如何
- vb.net - 反序列化时出现意外的节点类型元素错误