Home > Enterprise >  Remove specific string with quoted substring at the end
Remove specific string with quoted substring at the end

Time:04-06

I want to remove all occurrences of data-content="..." from my string.

The characters between the double quotes will change and are dynamic.

I have tried something like

gsub(/data-content=[^'"] K(.).*?\1/,'')

However, this does not match data-content="..." strings, how can I fix my regex?

CodePudding user response:

You can use

text.gsub(/\s*data-content="[^"]*"/, '')

See the regex demo and the Ruby demo online:

text = 'text data-content="abc123" string'
puts text.gsub(/\s*data-content="[^"]*"/, '')
## => text string

Details:

  • \s* - zero or more whitespaces
  • data-content=" - a fixed string
  • [^"]* - zero or more chars other than double quotes
  • " - a " char.

CodePudding user response:

If the content of the quotes is to be replaced by an empty string, use a positive lookbehind:

s = 'data-content="abc123"'
s.sub(/(?<=data-content=)".*?"/,'""')
=> "data-content=\"\""
  • Related