简体   繁体   中英

Replace s string in Ruby by gsub

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"
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.*}, ''

If the output have to be MT_Store_0

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

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM