具有嵌套分组的复杂Java正则表达式

时间:2014-01-27 18:56:39

标签: java regex

我正在尝试编写一个正则表达式,它将捕获我在Java中尝试匹配的内容,但似乎无法获得它。

这是我最近的尝试:

Pattern.compile( "[A-Za-z0-9]+(/[A-Za-z0-9]+)*/?" );

这就是我想要匹配的内容:

  • hello
  • hello/world
  • hello/big/world
  • hello/big/world/

这是我不想要的:

  • /
  • /hello
  • hello//world
  • hello/big//world

我很欣赏任何有关我做错事的见解:)

4 个答案:

答案 0 :(得分:0)

试试这个正则表达式:

Pattern.compile( "^[A-Za-z0-9]+(/[A-Za-z0-9]+)*/?$" );

答案 1 :(得分:0)

你的正则表达式最后是否需要问号?

我总是为我的正则表达式进行单元测试,这样我就可以操作它们直到它们通过。

答案 2 :(得分:0)

// your exact regex:
final Pattern regex = Pattern.compile( "[A-Za-z0-9]+(/[A-Za-z0-9]+)*/?" );

// your exact examples:
final String[]
    good = { "hello", "hello/world", "hello/big/world", "hello/big/world/" },
    bad = { "/", "/hello", "hello//world", "hello/big//world"};

for (String goodOne : good) System.out.println(regex.matcher(goodOne).matches());
for (String badOne : bad) System.out.println(!regex.matcher(badOne).matches());

打印true值的实心列。

换句话说:你的正则表达式完全正常。

答案 3 :(得分:0)

看起来你正在试图'捕获'被覆盖每个量化的itteration。只需更改括号内容即可。

  #  "[A-Za-z0-9]+((?:/[A-Za-z0-9]+)*)/?"

 [A-Za-z0-9]+ 
 (                                  # (1 start)
      (?: / [A-Za-z0-9]+ )*
 )                                  # (1 end)
 /?

或者,根本没有捕获 -

 #  "[A-Za-z0-9]+(?:/[A-Za-z0-9]+)*/?"

 [A-Za-z0-9]+ 
 (?: / [A-Za-z0-9]+ )*
 /?
相关问题