Search code examples
text-search

search a text in another text with the characters in the same order


I would like to search for a text ('needle') if it exists within another text ('haystack') with the following two conditions:

  1. all the characters of the 'needle' must be within the 'haystack' in the same order
  2. there can be any and unlimited other characters between subsequent characters of the 'needle' within the 'haystack'

Examples:

  • cde in abcde --> TRUE
  • cde in ab-c-de --> TRUE
  • cde in cabecd --> FALSE
  • cde in c-d!a+b5ce --> TRUE
  • cde in edc --> FALSE

Moreover 'cde' is not a constant string, instead a variable iterated over a list.

Any elegant solution in python or R or bash would be appreciated.


Solution

  • I got the solution in python:

    re.match('.*'+'.*'.join(list(needle))+'.*',(haystack))