1

How can I do a regexp in ruby 1.8 that matches:

/my_dir/1/file

but not if I have:

/my_dir/1/deeper_stuff/file

So far I have

 source_string = '/my_dir/1/index.html.erb'

 /^\/my_dir/.match(source_string)

for the initial match, how do I add the second disqualifier for /deeper_stuff ?

so that

 source_string = '/my_dir/1/deeper_stuff/'

gets excluded.

Michael Durrant
  • 93,410
  • 97
  • 333
  • 497
  • 1
    Not related but IMHO `source_string =~ /^\/my_dir(?!.*deeper_stuff)/` is better idea (I've used @kirilloid regexp). – Hauleth Mar 29 '12 at 20:36

3 Answers3

7

Negative look-ahead: /^\/my_dir(?!.*deeper_stuff)/.match(source_string)

kirilloid
  • 14,011
  • 6
  • 38
  • 52
1

/^/my_dir/\w*/\w+.\S*/.match(source_string) should work assuming all files end with a period and then some extension (to include multiple extensions such as .html.erb).

This works by searching for /my_dir/ followed by any number of word characters (letter, number, underscore) followed a forward-slash. This matches the next directory. Then we look for one or more word characters followed by a period followed by any number of non-whitespace characters. Thus, /my_dir/deeper_stuff/file.html.erb will be excluded because the additional directory causes the regex to not match.

Paul Simpson
  • 2,504
  • 16
  • 28
1

RE = Regexp.new("^/my_dir/1(/.+)?/file$")

def is_file(dir)
   (m = RE.match(dir)) && !m[1] ? "match" : "no match"
end

puts is_file("/my_file/1") #=> no match
puts is_file("/my_dir/1/file") #=> match
puts is_file("/my_dir/1/deeper_stuff/file") #=> no match
puts is_file("/my_dir/1/deeper/stuff/file") #=> no match

pgon
  • 55
  • 1