2015-10-17 37 views
3

我需要一个正则表达式模式,它将成功用于字符串​​,但不适用于字符串.*。我发现这个棘手。我期望[^.]\\*[^\\.]\\*(?<!\\.)\\*工作,但没有一个这样做。匹配星而不是星星

任何想法?

@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

这将是最好的总是描述你的实际使用情况,以避免陷阱的[XY问题](http://meta.stackexchange.com/questions/66377/what-is-the-xy-问题)。 –

+0

好点。这很困难,但基本上我在一个文件中有一个巨大的正则表达式,我试图匹配从某个服务器返回的JSON响应。我需要“。*”来忽略某些非确定性的部分。但'*'可能出现在服务器响应中。 –

+0

请说明它应该匹配什么类型的样本,哪些不应该。如果你只是需要它匹配“s *”,只需使用“s \\ *”正则表达式:) –

回答

2

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

愉快回答。 –

3

您的代码的问题在于它与非点字符匹配。您应该使用negative lookbehind代替:

(?<![.])[*] 

Regex101 demo.

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

Java demo.

+0

我试过这个,但奇怪的是它不起作用。我期待着它。 –

+0

因为你的if语句是错误的。 – Andreas

+0

不过,我得到''不匹配我想匹配的东西'' –

2

你的意思if (! ".*".matches(regex)) {