My app validates and imports data files for various vendors. One of the validations on the file will be to check whether it's filename is in the right format. I have my regex stored in my YAML file along with various other configurations as follows -
---
filename_regex: !ruby/regexp '/^input_.{1,10}_company_\d{8}.tsv$/'
check_header_row: true
foo: "Bar"
....
Essentially the above enforces that it has to be of format: input_companyName_company_20141127.tst
. I'm loading the file with YAML.load(filename)
in the app.
I'm running into 2 problems, as you may have already guessed
The curly braces don't escape correctly. When I take them out it works fine, so those are almost certainly the problem. Apparently \\
doesn't work for escaping, and neither does '
?
The \\d
needs to have it's own backslash escaped, I assume? In that case would I use \\\\d
in the file? That didn't seem to work either.
Thanks!
I can't seem to replicate any problem with what you already have.
Don't forget you probably want to be escaping the .
at the end for .tsv
and as someone already mentioned use \\A
and \\Z
instead of ^
and $
like '/\\Ainput_.{1,10}_company_\\d{8}\\.tsv\\Z/'
regex.yml
---
filename_regex: !ruby/regexp '/^input_.{1,10}_company_\d{8}.tsv$/'
foo: 'bar'
---
regex.rb
require 'yaml'
cfg = YAML.load_file('regex.yml')
valid_test_name = 'input_ABCD_company_12345678.tsv'
invalid_company_test_name = 'input_CompanyTooLong_company_12345678.tsv'
invalid_date_test_name = 'input_Company_company_12345678901.tsv'
valid_pass = valid_test_name =~ cfg["filename_regex"] ? 'pass' : 'fail'
invalid_company_pass = invalid_date_test_name =~ cfg["filename_regex"] ? 'pass' : 'fail'
invalid_date_pass = invalid_date_test_name =~ cfg["filename_regex"] ? 'pass' : 'fail'
puts "#{valid_test_name}: #{valid_pass}"
puts "#{invalid_company_test_name}: #{invalid_company_pass}"
puts "#{invalid_date_test_name}: #{invalid_date_pass}"
Running it ruby regex.rb
outputs
input_ABCD_company_12345678.tsv: pass
input_CompanyTooLong_company_12345678.tsv: fail
input_Company_company_12345678901.tsv: fail
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.