I want to find a search term in a given word. So we're speaking Regex.
The order of the letters is important, but I want to allow letters between each of the search term's letters.
An example : the german word seitenschneider contains the word seide in at least two ways:
word: seitenschneider
match 1: xxx.........xx.
match 2: ......x...xxxx.
I want to find the result with the least possible letters, so in this case I'd go with match 2.
Is there a way to do this with regex?
I tried making the wildcards ungreedy but didn't receive the desired result:
"seitenschneider".scan(/s.*?e.*?i.*?d.*?e/)
=> ["seitenschneide"]
What I want to achieve is:
"seitenschneider".scan(magic_regex_thingy)
=> ["schneide"]
I'd also be happy with something like
"seitenschneider".scan(another_magic_regex_thingy)
=> ["seitenschneide", "schneide"]
cause I can find the shortest word in there by myself.
Any hints on how to get there?
For your second question:
"seitenschneider".scan(/(?=(s.*?e.*?i.*?d.*?e))/).flatten
# => ["seitenschneide", "schneide"]
Getting the shortest one using the regex above:
"seitenschneider".scan(/(?=(s.*?e.*?i.*?d.*?e))/).flatten.min_by(&:length)
# => "schneide"
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.