有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java正则表达式:负前瞻

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

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

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

我认为第二个正则表达式很好。它将只匹配第二个字符串。但是,第一个正则表达式与这两个正则表达式都匹配。所以,我开始(第一次)用消极的前瞻性来玩弄。我设计了regex/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

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

谢谢


共 (1) 个答案

  1. # 1 楼答案

    试一试

    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字符)之间的空格。因此,它在{}中的{}之前或之后匹配,但在{}中的{}和{}之间无法匹配

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