Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Regular Expression: Find the last punctuation

Tags:

regex

ruby

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!

like image 516
ardavis Avatar asked Dec 10 '25 19:12

ardavis


2 Answers

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

like image 89
Mark Byers Avatar answered Dec 12 '25 09:12

Mark Byers


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"
like image 44
undur_gongor Avatar answered Dec 12 '25 07:12

undur_gongor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!