Eli Foster
Eli Foster

Reputation: 68

Escaped apostrophes and regular expression

I have a string that I am attempting to gather some specific data from. I'm able to narrow down that the given string (which has an escaped apostrophe \') is inside the main string. However, when I scan it for the string, using #{string}, it finds no results.

I am pretty certain that this is because when an escaped apostrophe \' is in double quotes, it becomes "Str\'ing", which is what it would look like in the main string. However, once interpolated into a regular expression, it stays as "Str\\'ing", which can't be found.

I suppose my question is how should I properly handle this? I'm sure the solution would either be a better regular expression, or a better substitution, but I don't know what those would be.

Here is some sample code:

text = "STR = {'Str\'ing', ... }"
thing = "Str'ing"
thing.gsub!("'") { "\\'" }
if text.include?("= {'#{thing}',") # => true
  match_data = text.scan(/([A-Z0-9\-]+) = {'#{thing}',/)
  p match_data
  # => []
end

Upvotes: 0

Views: 431

Answers (2)

Eli Foster
Eli Foster

Reputation: 68

There's surely a better way to do this, but it seems to work for my purposes. I changed the first gsub! call to thing.gsub!(/'/) { "\\'" } to make the include? call true. Then I added an additional thing.gsub!(/\'/) { "\\'" } so that the regex can actually find it.

Upvotes: 1

Travis Smith
Travis Smith

Reputation: 542

You can do away with the gsub! call since the \' will be interpreted as '. You can also simplify the regular expression to /\w+ = {'#{thing}',/ since you really just need to match a single word before the = sign. So like this

    text = "STR = {'Str\'ing', ...}"
    thing = 'Str\'ing'
    if text.include?("= {'#{thing}',") 
      match_data = text.scan(/\w+ = {'#{thing}',/)
      puts match_data
    end

Upvotes: 0

Related Questions