35

我正在尝试制作两个匹配 URI 的正则表达式。这些 URI 的格式为:/foo/someVariableData/foo/someVariableData/bar/someOtherVariableData

我需要两个正则表达式。每个都需要匹配一个,而不是另一个。

我最初想出的正则表达式分别是: /foo/.+/foo/.+/bar/.+

我认为第二个正则表达式很好。它只会匹配第二个字符串。然而,第一个正则表达式匹配两者。所以,我开始(第一次)用消极的前瞻来玩。我设计了正则表达式/foo/.+(?!bar)并设置了以下代码来测试它

public static void main(String[] args) {
    String shouldWork = "/foo/abc123doremi";
    String shouldntWork = "/foo/abc123doremi/bar/def456fasola";
    String regex = "/foo/.+(?!bar)";
    System.out.println("ShouldWork: " + shouldWork.matches(regex));
    System.out.println("ShouldntWork: " + shouldntWork.matches(regex));
}

而且,当然,他们俩都决心true.

有人知道我在做什么错吗?我不一定需要使用负前瞻,我只需要解决问题,我认为负前瞻可能是一种方法。

谢谢,

4

1 回答 1

63

尝试

String regex = "/foo/(?!.*bar).+";

或者可能

String regex = "/foo/(?!.*\\bbar\\b).+";

以避免在/foo/baz/crowbars我假设您确实希望该正则表达式匹配的路径上出现故障。

说明:(没有 Java 字符串所需的双反斜杠)

/foo/ # Match "/foo/"
(?!   # Assert that it's impossible to match the following regex here:
 .*   #   any number of characters
 \b   #   followed by a word boundary
 bar  #   followed by "bar"
 \b   #   followed by a word boundary.
)     # End of lookahead assertion
.+    # Match one or more characters

\b,“单词边界锚”,匹配字母数字字符和非字母数字字符之间的空白空间(或字符串的开头/结尾和 alnum 字符之间)。因此,它在in之前b或之后匹配,但在and in之间不匹配。r"bar"wb"crowbar"

Protip:看看http://www.regular-expressions.info - 一个很棒的正则表达式教程。

于 2012-06-20T18:03:52.433 回答