[英]Complex Java Regular Expression with Nested Groupings
我正在嘗試編寫一個正則表達式,該正則表達式將捕獲我在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
我將不勝感激對我做錯的事情的了解:)
試試這個正則表達式:
Pattern.compile( "^[A-Za-z0-9]+(/[A-Za-z0-9]+)*/?$" );
您的正則表達式最后不需要問號嗎?
我總是為我的正則表達式編寫單元測試,因此我可以擺弄它們直到通過。
// 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
值的實線。
換句話說,您的正則表達式完全可以正常使用。
您似乎要“捕獲”的內容已被每個量化的信號覆蓋。 只需更改括號的排列即可。
# "[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]+ )*
/?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.