匹配星而不是星星
问题描述:
我需要一个正则表达式模式,它将成功用于字符串,但不适用于字符串.*
。我发现这个棘手。我期望[^.]\\*
或[^\\.]\\*
或(?<!\\.)\\*
工作,但没有一个这样做。匹配星而不是星星
任何想法?
@Test
public void testTemp() {
String regex = "[^.][*]";
if ("s*".matches(regex)) {
if (".*".matches(regex)) {
System.out.println("Success");
} else {
// This exception gets thrown.
throw new RuntimeException("Wrongly matches dot star");
}
} else {
throw new RuntimeException("Does not match star");
}
}
请不要告诉我,我的用例是愚蠢的。我有一个完全合法的用例,它有点难以清晰地表达。我只想说,我并不困惑。
答
的模式是正确的,只是你的第二个if
说法是错误的尝试这个
@Test
public void testTemp() {
String regex = "[^.][*]";
if ("s*".matches(regex)) {
if (!".*".matches(regex)) {
System.out.println("Success");
} else {
// This exception gets thrown.
throw new RuntimeException("Wrongly matches dot star");
}
} else {
throw new RuntimeException("Does not match star");
}
}
+0
是的,这是有效的。 –
+0
愉快回答。 –
答
您的代码的问题在于它与非点字符匹配。您应该使用negative lookbehind代替:
(?<![.])[*]
Pattern regex = Pattern.compile("(?<![.])[*]");
if (regex.matcher("s*").find()) {
if (!regex.matcher(".*").find()) {
System.out.println("Success");
} else {
// This exception gets thrown.
throw new RuntimeException("Wrongly matches dot star");
}
} else {
throw new RuntimeException("Does not match star");
}
答
你的意思if (! ".*".matches(regex)) {
这将是最好的总是描述你的实际使用情况,以避免陷阱的[XY问题](http://meta.stackexchange.com/questions/66377/what-is-the-xy-问题)。 –
好点。这很困难,但基本上我在一个文件中有一个巨大的正则表达式,我试图匹配从某个服务器返回的JSON响应。我需要“。*”来忽略某些非确定性的部分。但'*'可能出现在服务器响应中。 –
请说明它应该匹配什么类型的样本,哪些不应该。如果你只是需要它匹配“s *”,只需使用“s \\ *”正则表达式:) –