0

What is a good regex to match the entire string, unless the string is "/"?

Use case:This is for a rewrite rule. Working with rack-rewrite, which is appending a trailing /.

I need:

/foo -> /newpath/foo
/ -> newpath

The second example does not have a trailing slash.

Took a look at Regex - Match Entire String Unless but didn't know how to make it work for all except "/".

Working in Ruby.

Community
  • 1
  • 1
B Seven
  • 44,484
  • 66
  • 240
  • 385

2 Answers2

2

It is entirely wrong to use a regex for this purpose, but per your request:

re = %r{(?!\A/\z)(\A.*\z)}

"foo"[re] #=> "foo"
" /"[re]  #=> " /"
"/ "[re]  #=> "/ "
"/"[re]   #=> nil

If you want to get the string unless a string is "/", the way to do it is:

string unless string == "/"
sawa
  • 165,429
  • 45
  • 277
  • 381
  • I added its use to the answer. – sawa Jul 20 '13 at 03:46
  • If it is entirely wrong to use a regex for this purpose, how would you do it? – B Seven Jul 20 '13 at 03:47
  • The regex works. It just needs to escape the forward slash: `(?!\A\/\z)(\A.*\z)` – B Seven Jul 20 '13 at 03:48
  • Yes, but this is part of a rewrite rule. I don't know how to add ruby to the match part...but maybe it could be done with 2 rules. I agree with you. This is a very cryptic solution. – B Seven Jul 20 '13 at 03:54
  • 1
    You're right. It is easier and clearer to do it with 2 rules: `rewrite %r{/foo(.*)}, '/newpath/foo$1' rewrite %r{/(.*)}, '/newpath$1'` – B Seven Jul 20 '13 at 04:20
  • Your two rule solution doesn't produce the mapping you said you wanted in your op. – 7stud Jul 20 '13 at 04:47
1
rewrite %r{.*}, lambda { |match, rack_env|
    url = match[0]
    url == "/" ? "newpath" : "/newpath#{url}"
  }
7stud
  • 46,922
  • 14
  • 101
  • 127
  • your solution is a bit interesting to me... But would like to know why did you use `lambda` ? – Arup Rakshit Jul 20 '13 at 05:12
  • 1
    @Priti, The op already did in one of the comments. Here it is again: https://github.com/jtrupiano/rack-rewrite – 7stud Jul 20 '13 at 05:56