简体   繁体   English

Ruby:使用正则表达式的.grep

[英]Ruby: .grep with regex

I'm using a regular expression to replace all '*' with '[A-Za-z0-9]*' except when the '*' is preceded by '\\' like '\\*' . 我正在使用正则表达式将所有'*'替换为'[A-Za-z0-9]*'除非在'*'之前加上'\\''\\*' How can I ignore the case '\\*' ? 如何忽略大小写'\\*'

code: 码:

puts Regexp.new(val.gsub(/^\*/,'[A-Za-z0-9]*')) =~ str ? 'true' : 'false'  

You can do this by being more particular in your substitutions: 您可以通过在替换中更具体地做到这一点:

tests = [
  "*.foo",
  "\\*.foo"
]

tests.each do |test|
  r = test.gsub(/(\\\*|\*)/) do |s|
    case ($1)
    when "\\*"
      $1
    else
      "[A-Za-z0-9]*"
    end
  end

  puts r
end

Results for me: 结果给我:

[A-Za-z0-9]*.foo
\*.foo

The first capture looks for \\* specifically. 第一个捕获专门查找\\*

You can use a Negative Lookbehind assertion here. 您可以在此处使用负向后隐式断言。

"foo\\* bar* baz* quz\\*".gsub(/(?<!\\)\*/, '[A-Za-z0-9]*')
# => 'foo\* bar[A-Za-z0-9]* baz[A-Za-z0-9]* quz\*'

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

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