I need help in understanding how the following works.
"middl'-.*$%ddlemiddlemiddlemiddlemiddlemiddlemiExcess".gsub(/[^a-zA-Z'-.]/, '')
# => "middl'-.*ddlemiddlemiddlemiddlemiddlemiddlemiExcess"
"middl'-.*$%ddlemiddlemiddlemiddlemiddlemiddlemiExcess".gsub(/[^a-zA-Z.'-]/, '')
# => "middl'-.ddlemiddlemiddlemiddlemiddlemiddlemiExcess"
When I give /[^a-zA-Z'-.]/
, then the star is not removed, but in the second example, the star is removed. Why?
I want the result after gsub
to have only letters ( a-zA-Z
), period ( .
), hypen ( -
), single apostphe ( '
) to exist. Just by changing the period position inside regular expression the output is different ?
In /[^a-zA-Z'-.]/
hyphen is treated as range delimiter, exactly as in AZ
before. The range is:
▶ ("'"..'.').to_a
#⇒ ["'", "(", ")", "*", "+", ",", "-", "."] # note asterisk
In /[^a-zA-Z.'-]/
hyphen is the last symbol and hence it is treated as hyphen itself.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.