简体   繁体   English

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

[英]Complex Java Regular Expression with Nested Groupings

I am trying to get a regular expression written that will capture what I'm trying to match in Java, but can't seem to get it. 我正在尝试编写一个正则表达式,该正则表达式将捕获我在Java中试图匹配的内容,但似乎无法获取。

This is my latest attempt: 这是我最近的尝试:

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

This is what I want to match: 这是我要匹配的:

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

This what I don't want matched: 这是我不想匹配的:

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

I'd appreciate any insight into what I am doing wrong :) 我将不胜感激对我做错的事情的了解:)

试试这个正则表达式:

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

Doesn't your regex require question mark at the end? 您的正则表达式最后不需要问号吗?

I always write unit tests for my regexes so I can fiddle with them until they pass. 我总是为我的正则表达式编写单元测试,因此我可以摆弄它们直到通过。

// 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());

prints a solid column of true values. 打印一列true值的实线。

Put another way: your regex is perfectly fine just as it is. 换句话说,您的正则表达式完全可以正常使用。

It looks like what you're trying to 'Capture' is being overwritten each quantified itteration. 您似乎要“捕获”的内容已被每个量化的信号覆盖。 Just change parenthesis arangement. 只需更改括号的排列即可。

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

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

Or, with no capture's at all - 或者,完全没有捕获内容-

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM