我在使用正则表达式时遇到问题,所以我想我会在这里问。基本上,我需要它来匹配一个集合的 URI,除了某个(/new
)。
IE:
/properties # match
/properties/25 # match
/properties/new # rejected
我尝试了以下变体,但无济于事:
/properties(^(/new)).*
我认为我的麻烦在于否定,但我不能完全理解我的意思是做什么..对解决方案的解释将不胜感激!
我在使用正则表达式时遇到问题,所以我想我会在这里问。基本上,我需要它来匹配一个集合的 URI,除了某个(/new
)。
IE:
/properties # match
/properties/25 # match
/properties/new # rejected
我尝试了以下变体,但无济于事:
/properties(^(/new)).*
我认为我的麻烦在于否定,但我不能完全理解我的意思是做什么..对解决方案的解释将不胜感激!
^
negates inside a character class (a group of characters in any order surrounded by [ ]
. You need to use ?!
. You also shouldn't use .*
. It doesn't add anything. If you want to match anything you just don't put anything :). Also you don't need to capture the match. Depending on how you're setting it up you may also need to escape the slashes ( /
)
Try this:
\/properties(?!\/new)
How about this one:
/properties(?!/new)(?:/.*){0,1}
the: `(?!/new) is a negative forward lookup, and essentially says: make sure this cannot be matched
the following: (?:/.+){0,1} allows for the matching of additional paths (ie. /25) and is a non-capturing group that says match / followed by zero or more characters, and match it zero to one times as a group. The {0,1} allows it to match even if there is no /25.