Java 匹配星号,但不匹配点星号

Java 匹配星号,但不匹配点星号,java,regex,Java,Regex,我需要一个正则表达式模式,它将成功地用于strings*,但不能用于string*。我觉得这很棘手。我希望[^.]\*或[^\.]\*或(?)能起作用,但这些都不行 有什么想法吗 @Test public void testTemp() { String regex = "[^.][*]"; if ("s*".matches(regex)) { if (".*".matches(regex)) { System.out.println("S

我需要一个正则表达式模式,它将成功地用于string
s*
,但不能用于string
*
。我觉得这很棘手。我希望
[^.]\*
[^\.]\*
(?)能起作用,但这些都不行

有什么想法吗

@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");
    }
}

请不要告诉我我的用例是愚蠢的。我有一个完全合法的用例,它有点难以清楚地表达。只需说一句,我并不感到困惑。

您的代码的问题是它也匹配非点字符。您应该改为使用:

(?


Pattern regex=Pattern.compile((?你的意思是
if(!“*”.matches(regex)){

模式是正确的,只是你的第二个
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");
    }
}

最好总是描述您的实际用例,以避免出现.Good point的陷阱。这很难,但基本上我在一个文件中有一个巨大的正则表达式,我试图匹配从某个服务器返回的JSON响应。我需要”*忽略某些不确定的部分。但是
*
很可能会出现在服务器响应中。请指定它应该匹配什么样的示例,什么不应该匹配。如果您只需要它匹配“s*”,只需使用“s\*”regexp:)我尝试了这个方法,但奇怪的是它不起作用。我本来希望它能匹配。但是,我还是得到了
“与我想要匹配的不匹配”
您的正则表达式很好。保留它。@当使用
matches()
时,此正则表达式无法工作,因为它只匹配1个字符
*
,后面的查找永远都不可能是真的。它与演示使用的
find()
一起工作很好。@Sridhar Sarnobat
[^。]\\*
当星号是字符串中的第一个或唯一一个字符时不起作用。回答起来很愉快。
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");
}
@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");
    }
}