Looking for regex to use with #gsub in Ruby to strip all digits in a string except for ordinals. Assume the following is fine to preserve what I want in a string:
string = "100 red balloons"
strip_digits = string.gsub(/[^a-zA-Z\s]/, '')
=> " red balloons"
string = "50th red balloon"
=> "50th red balloon"
Just as a "fix" of your regex, I suggest:
See IDEONE demo here
The logic is the following: match and capture into group 1 all the numbers followed with the ordinal numeral suffixes, and then restore this value with the
\1 backreference in the replacement pattern, and then match (to remove) all the non-letters and non-spaces with
(\d+(?:th|[rn]d|st))- Group 1 matching 1+ digits (
\d+) followed with either
st(all substring is stored in a numbered buffer #1, that is accessed when the
\1backreference is used in the replacement pattern)
[^a-z\s]- a character other than an ASCII letter (all lower- and uppercase letters are matched due to the
/icase insensitive modifier) and a whitespace (to avoid removing Unicode letters, use