Home > Software design >  GSUB replace 3 or more repeating characters
GSUB replace 3 or more repeating characters

Time:10-31

A little help would be appreciated with a gsub regex in ruby. I need to replace 3 or more forward slashes "//////" with just 2 forward slashes "//" in a string of text. However, a single forward slash and double forward slashes should be skipped and left as is.

my data looks like this jeep/grand cherokee////////hyundai/////harley davidson//bmw and should be converted to jeep/grand cherokee//hyundai//harley davidson//bmw

I don't have much experience with using gsub regex's, here's a few things I've tried but they either strip out all forward slashes or add in too many.

  vehicles = vehicles.gsub(/[\/\\1{3,}]/, "")

  vehicles = vehicles.gsub(/[\/\2 ]/, "//")

  vehicles = vehicles.gsub(/[\/{3,}]/,"//")

CodePudding user response:

When you enclose the whole pattern inside square brackets, you make it match a single char.

Your regexps mean:

  • [\/\\1{3,}] - a single char, /, \, 1, {, 3, , or }
  • [\/\2 ] - /, \u0002 char or
  • [\/{3,}] - /, {, 3, , or }

You can use

s.gsub(/\/{3,}/, '//')

See the Ruby demo online.

  • Related