I am trying to find the last punctuation or space character in a sentence.
Given I have the sentence, "Hello! What is your name?"
I want the regular expression to return the index of the ?, but my regex is returning the index of the !
My attempt:
> s = "Hello! What is your name?"
> s =~ /([[:punct:]\s])/
> puts $+
!
=> nil
I believe $+ returns the highest match, so the last match, but it's only matching the first.
Thoughts? Thanks in advance!
To find the last match use rindex:
s = "Hello! What is your name?"
i = s.rindex(/[[:punct:]]/)
puts i
Result:
24
See it working online: ideone
The match against
/[[:punct:]\s][^[:punct]\s]*\z/
results in 24 for your example.
The regexp matches a punctuation or space followed by only non-punctuation-or-space characters and then the string end. So, it will find the last punctuation/space in the string.
$+ does not help because it does not magically match the regexp several times. It just returns the last group of the most recent match. If you have e.g. 7 groups in your expression it will be equal to $7.
"abcdefghijklmnopq" =~ /(.)(.)(.)(.)(.)(.)(.)/ # 0
$+ # "g"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With