0

I'm trying to remove a pattern from a string using the ruby gsub method. Given the following string:

ANTONIO JUAREZ HAMPEL SCHLICH- TING

I need to remove only the hyphen at end of line and turn the string into a single line, like ANTONIO JUAREZ HAMPEL SCHLICHTING. I tried:

name = <<-TEXT
  ANTONIO JUAREZ HAMPEL SCHLICH-
  TING
TEXT

name.gsub(/[a-zA-Z](\-\n)/, '')

But it don't worked. The gsub should remove ONLY the (\-\n) immediately after any non-numeric character ([a-zA-Z]).

Searching here, at SO, I figured out through this question that gsub ignore the regexp group and do the substitution for all the pattern. Are there an option to gsub in ruby, or a different way on using this method that I can achieve this result?

Community
  • 1
  • 1
Pedro Vinícius
  • 476
  • 6
  • 13

5 Answers5

2
name.gsub!(/(?<=[A-Za-z])-\n\s*/, '')

"Replace a dash, a newline and any number of spaces that are preceded by a letter, with nothing"

A lookbehind ((?<=...)) is not considered to be a part of the match. Alternately, you could capture the letter in a capture group and then re-insert it in the replacement, but it is less elegant.

Amadan
  • 191,408
  • 23
  • 240
  • 301
1

Just out of curiosity:

▶ name = <<-TEXT
▷   ANTONIO JUAREZ HAMPEL SCHLICH-
▷   TING
▷ TEXT
#⇒ "  ANTONIO JUAREZ HAMPEL SCHLICH-\n  TING\n"
▶ name.split(/-\n\s*/).join
#⇒ "  ANTONIO JUAREZ HAMPEL SCHLICHTING\n"

or, to get rid of leading/trailing spaces:

▶ name.split(/-\n/).map(&:strip).join
#⇒ "ANTONIO JUAREZ HAMPEL SCHLICHTING"
Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160
1

Why do you think you must use a regex?

name.split('-').map(&:strip).join
  #=> "ANTONIO JUAREZ HAMPEL SCHLICHTING"
Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100
0

try this:

your_string.gsub!(/-\n\s*/, '')
#=> "ANTIONO JUAREZ HAMPEL SCHLITICH\n"
Bartłomiej Gładys
  • 4,525
  • 1
  • 14
  • 24
0

Try this:

name = <<-TEXT
  ANTONIO JUAREZ HAMPEL SCHLICH-
  TING
TEXT


puts name.gsub(/^\s+/,'').gsub(/(?<=[a-zA-Z])(\-\n)/,'')

OUTPUT:

ANTONIO JUAREZ HAMPEL SCHLICHTING
Tiago Lopo
  • 7,619
  • 1
  • 30
  • 51