I'm using a regular expression to replace all '*' with '[A-Za-z0-9]*' except when the '*' is preceded by '\' like '\*'. How can I ignore the case '\*' ?
code:
puts Regexp.new(val.gsub(/^\*/,'[A-Za-z0-9]*')) =~ str ? 'true' : 'false'
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\*'
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.