0

I have a string with exclamation marks. I want to remove the exclamation marks at the end of the word, not the ones before a word. Assume there is no exclamation mark by itself/ not accompanied by a word. By word I mean [a..z], can be uppercased.

For example:

exclamation("Hello world!!!")
#=> ("Hello world")

exclamation("!!Hello !world!")
#=> ("!!Hello !world")

I have read How do I remove substring after a certain character in a string using Ruby? ; these two are close, but different.

def exclamation(s)
  s.slice(0..(s.index(/\w/)))
end

# exclamation("Hola!") returns "Hol"

I have also tried s.gsub(/\w!+/, ''). Although it retains the '!' before word, it removes both the last letter and exclamation mark. exclamation("!Hola!!") #=> "!Hol".

How can I remove only the exclamation marks at the end?

Community
  • 1
  • 1
Iggy
  • 5,129
  • 12
  • 53
  • 87

3 Answers3

1

Although you haven't given a lot of test data, here's an example of something that might work:

def exclamation(string)
  string.gsub(/(\w+)\!(?=\s|\z)/, '\1')
end

The \s|\z part means either a space or the end of the string, and (?=...) means to just peek ahead in the string but not actually match against it.

Note that this won't work in the case of things like "I'm mad!" where the exclamation mark is not adjacent to a space, but you could always add that as another potential end-of-word match.

tadman
  • 208,517
  • 23
  • 234
  • 262
1
"!!Hello !world!, world!! I say".gsub(r, '')
  #=> "!!Hello !world, world! I say"

where

r = /
    (?<=[[:alpha:]])  # match an uppercase or lowercase letter in a positive lookbehind
    !                 # match an exclamation mark
    /x                # free-spacing regex definition mode

or

r = /
    [[:alpha:]]       # match an uppercase or lowercase letter
    \K                # discard match so far
    !                 # match an exclamation mark
    /x                # free-spacing regex definition mode

If the above example should return "!!Hello !world, world I say", change ! to !+ in the regexes.

Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100
1

If you don't want to use regex that sometimes difficult to understand use this:

def exclamation(sentence)
  words = sentence.split
  words_wo_exclams = words.map do |word|
    word.split('').reverse.drop_while { |c| c == '!' }.reverse.join
  end
  words_wo_exclams.join(' ')
end
Evmorov
  • 1,134
  • 22
  • 28