简体   繁体   中英

Ruby gsub pattern

I have the following string:

Rib Franzido - La Mandinne

I need to change the spaces to dash (-):

blusa-rib-franzido-la-mandinne

But using gsub I got this: blusa-rib-franzido---la-mandinne

Code: string.downcase.strip.gsub(' ', '-')

How can I solve that? Thanks

Just squeeze the dashes:

"Rib Franzido - La Mandinne".tr(" ", "-").squeeze("-")  # => "Rib-Franzido-La-Mandinne"

One way would be one way to do it using regex that first replaces spaces between words, then another gsub to remove other spaces.

"Rib Franzido - La Mandinne".downcase.gsub(/(?<=\w)\s(?=\w)/, '-').gsub(' ', '')
 => "rib-franzido-la-mandinne"
"Rib Franzido - La Mandinne".gsub(/ - | /, '-')
  #=> "Rib-Franzido-La-Mandinne"

The regular expression attempts to match " - " or a single space, in that order. If a match is made it is converted to a hypen. If multiple consecutive spaces may be present you may wish to modify the regular expression as follows.

"Rib    Franzido    -  La  Mandinne".gsub(/ +- +| +/, '-')
  #=> "Rib-Franzido-La-Mandinne" 

In old-school/classic Perl-compatible Regex Style:

"Rib Franzido - La Mandinne".gsub(/\s*-+\s*|\s+/, '-')

This matches all types of spaces before and after dashes and multiple spaces/dashes.

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