简体   繁体   English

如何使用Ruby在YAML中逃避花括号和反斜杠?

[英]How to escape curly braces and backslashes in YAML with Ruby?

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 - 我有我的正则表达式存储在我的YAML文件中以及如下的各种其他配置 -

---
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 . 基本上上面强制它必须是格式: input_companyName_company_20141127.tst I'm loading the file with YAML.load(filename) in the app. 我在应用程序中使用YAML.load(filename)加载文件。

I'm running into 2 problems, as you may have already guessed 你可能已经猜到了,我遇到了两个问题

  1. 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 ' ? 显然\\不适用于逃避,也没有'

  2. The \\d needs to have it's own backslash escaped, I assume? 我想, \\d需要让它自己的反斜杠逃脱吗? In that case would I use \\\\d in the file? 在那种情况下,我会在文件中使用\\\\d吗? 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/' 最后为.tsv和已经提到的人使用\\A\\Z而不是^$ like '/\\Ainput_.{1,10}_company_\\d{8}\\.tsv\\Z/' \\A . .tsv \\Z '/\\Ainput_.{1,10}_company_\\d{8}\\.tsv\\Z/'

regex.yml regex.yml

---
filename_regex: !ruby/regexp '/^input_.{1,10}_company_\d{8}.tsv$/'
foo: 'bar'
---

regex.rb 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 运行它ruby regex.rb输出

input_ABCD_company_12345678.tsv: pass
input_CompanyTooLong_company_12345678.tsv: fail
input_Company_company_12345678901.tsv: fail

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM