1

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?

0

1 Answer 1

4

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"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.