views:

31

answers:

2

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 prefix 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.

+1  A: 
^(?!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
Tomalak
Thanks so much for your awesome answer, it works well, and I will no doubt select your answer. But I was wondering if you could tell me how to modify the regex so that it could also select an empty string?Thanks so much!
Mark Rogers
Use `.*` in place of `.+`.
Tomalak
+1  A: 

Try a look-ahead assertion:

^(?!s1).*(home)

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

Gumbo
Thanks for the info!
Mark Rogers