I want to separate a string into two parts if a token from an array is found at the end of the string. I have tried this:
x = "Canton Female"
GENDER_TOKENS = ["m", "male", "men", "f", "w", "female", "wom"]
x.partition(/(^|[[:space:]]+)[#{Regexp.union(GENDER_TOKENS)}]$/i)
#=> ["Canton Female", "", ""]
But although the word "female" is part of my tokens, it is not getting split out. How do I adjust my regex so that it gets split properly?
I'm a little unclear what you are asking - what is the desired result? However, here's what I think you're looking for:
String#split
will split the string on each match; unlikeString#partition
, which returns[head, match, tail]
. I think that's probably what you wanted?\b
is a word boundary anchor. This is a cleaner solution than trying to match on "start of line or whitespace".Regexp#source
returns only the inner "text" of the regexp; unlike the (implicit)Regexp#to_s
you were using, which returns the full object including option toggles - i.e./(?-mix:m|male|men|f|w|female|wom)/