JUnit怎么判断字符串符合正则?
使用 assertthat 配合 matchespattern 方法即可验证字符串是否符合正则表达式。需要引入 org.hamcrest.matchers.matchespattern,传入预期的正则字符串和待测字符串,若匹配成功则测试通过,否则抛出异常。

import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.matchesPattern;
public class RegexTest {
@Test
public void testEmail() {
String email = "test@example.com";
assertThat(email, matchesPattern("^[\w-]+@[\w-]+\.[a-z]{2,}$"));
}
}
如何验证字符串不符合正则?
使用 not(matchesPattern(...)) 组合断言来验证字符串不符合特定正则。将 matchesPattern 作为参数传递给 not 方法,当字符串不匹配正则时测试通过。

import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.matchesPattern;
public class RegexNegativeTest {
@Test
public void testInvalidEmail() {
String invalid = "invalid-email";
assertThat(invalid, not(matchesPattern("^[\w-]+@[\w-]+\.[a-z]{2,}$")));
}
}
基于程序中某个输入、条件或结果的具体问题
当正则表达式包含特殊字符如反斜杠时,Java字符串中需使用双反斜杠转义,例如 \d 表示数字。在JUnit测试中,务必确保正则字符串的转义正确,否则会导致匹配失败或编译错误。

















