0

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'  

2 Answers 2

1

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\*'
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.