开发者

How do I write a regex that ignores strings starting with a particular prefix, and captures everything else into a single group?

Background:

I'm trying to come up with a regex for a rewrite rule that will take anything that does not start with a particular prefix, and add that prefix to it. But urls that already have the prefix should be rejected by the regular expression (because they already have the url).

Example:

If the prefi开发者_Python百科x is s1 a string like home will capture the home part. But a string like s1/home, will not capture anything.

This way I can add the capture group onto the prefix, so that 'home' will become 's1/home'.

I've tried (^s1/), but I'm missing something here, because that rejected 'home' for some reason.


^(?!prefix)(.+)

replace with

prefix$1

Explanation:

^         # start-of-string
(?!       # begin negative look-ahead
  prefix  # your prefix (take care to properly regex-escape it)
)         # end negative look-ahead
(.+)      # capture the complete string to group $1


Try a look-ahead assertion:

^(?!s1).*(home)

This will match home in any string that does not start with s1.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜