0

我编写了一个正则表达式,它适用于我能想到的所有测试用例。基本上任何与该模式匹配的 URL:

/app.* AND 最后没有长度为 1-4 的扩展名,应该重写。我想出了:

/app((?:\\/[\\w([^\\..]{1,4}\b)\\-]+)+)

问题是,这可以简化以实现相同的目标吗?另外,我是否可以用 .* 之类的东西替换我对 \w 的使用,我可能是错的,但我怀疑一旦遇到带有奇数字符的 URL,它就会中断。

编辑 1:应该匹配的示例 URL:

/app AND /app/
/app/auth
/app/auth/fb
/app/auth/twitter
/app/groups
/app/conn/manage
/app/play
/app/play/migrate
/app/play/migrate/done

不应匹配的示例 URL:

/app/js/some.file.js
/app/js/jquery.js
/app/styles/default/rain.css
/app/styles/name/file.css
/app/tpl/index.tpl
/app/tpl/file.html
/app/tpl/some.other.tpl

谢谢。

4

2 回答 2

2

I think a better approach is to put all the assets you want the webserver to handle in a single directory. Like /app/public, so you would get app/public/js and app/public/html etc. This will make you have no edge cases and a far easier URL handling.

Anyway, I think the regex below answers the question you asked: match anything except if there is a extension with 1 - 4 characters on the file.

^(\/(\w+))*\/?(\.\w{5,})?\??([^.]+)?$

http://rubular.com/r/4CQ4amccH5

^              //start of anchor
  (
    \/         //match forward slash
    (\w+)      //match any word character, match atleast once 
  )+           //match this group atleast once (this group captures /app/etc/etc)
  \/?          //match a forward slash, make it optional (to also capture /app/)
  (\.\w{5,})?  //match any word after a . with 5 characters or more, make it optional
  \??          //match a ?, make the match optional
  ([^.]+)?     //match anything not containing a . 1 or more times, make the match optional
$              //end of anchor

This still needs some work to make it work in Java, mainly alot of escaping escape characters.

于 2013-01-31T10:16:22.653 回答
0

Your regex would be:

/app(/\w+)*/?$

I assumed you want to match a url with word characters that may end up with a slash but not a file extension.

于 2013-01-31T10:34:25.000 回答