Replace s string in Ruby by gsub

291 views Asked by At

I have a string

path = "MT_Store_0  /47/47/47/opt/47/47/47/data/47/47/47/FCS/47/47/47/oOvt4wCtSuODh8r9RuQT3w"

I want to remove the part of string from first /47 using gsub.

path.gsub! '/47/', '/'

Expected output:

"MT_Store_0  "

Actual output:

"MT_Store_0  /47/opt/47/data/47/FCS/47/oOvt4wCtSuODh8r9RuQT3w"
3

There are 3 answers

1
Yu Hao On
path.gsub! /\/47.*/, ''

In the regex, \/47.* matches /47 and any characters following it.

Or, you can write the regex using %r to avoid escaping the forward slashes:

path.gsub! %r{/47.*}, ''
0
Cédric ZUGER On

If the output have to be MT_Store_0

then gsub( /\/47.*/ ,'' ).strip is what you want

0
Cary Swoveland On

Here are two solutions that employ neither Hash#gsub nor Hash#gsub!.

Use String#index

def extract(str)
  ndx = str.index /\/47/
  ndx ? str[0, ndx] : str
end

str = "MT_Store_0  /47/47/oOv"
str = extract str
  #=> "MT_Store_0  "

extract "MT_Store_0 cat"
  #=> "MT_Store_0 cat"

Use a capture group

R = /
    (.+?)  # match one or more of any character, lazily, in capture group 1
    (?:    # start a non-capture group 
      \/47 # match characters
      |    # or
      \z   # match end of string
    )      # end non-capture group
    /x     # extended mode for regex definition

def extract(str)
  str[R, 1]
end

str = "MT_Store_0  /47/47/oOv"
str = extract str
  #=> "MT_Store_0  "

extract "MT_Store_0  cat"
  #=> "MT_Store_0  cat"