Home > Blockchain >  Find a substring in parts within a string
Find a substring in parts within a string

Time:03-16

I'm learning Python, and came across a situation where I have to find a substring within a string but in parts.

For example, my string could be My string="this is stack overflow" OR My string="this stack is overflow"

And i have to find if stack overflow is present.

The order must be same, but there can be anything written in between two portions that is stack and overflow.

Any help is appreciated.!

CodePudding user response:

use regular expression, code below

import re

mystr = ["this is stack overflow", "this stack is overflow"]
my_key = "stack overflow"


rexpr = re.compile(".*".join(my_key.split()))
for s in mystr:
    print(re.search(rexpr, s))

output

<re.Match object; span=(8, 22), match='stack overflow'>
<re.Match object; span=(5, 22), match='stack is overflow'>

CodePudding user response:

You can do this several ways. The two I can think of are:

  1. Regular expressions
  2. Finding two strings in the same string.
s1 = "this is stack overflow"
s2 = "this stack is overflow"

Using regular expressions you can do it this way:

re_so = re.compile('stack(.*)overflow') #Here's the regex to use...
if m := re_so.search(s1):
    print('We have a match')
else:
    print('No match...')
if m := re_so.search(s2):
    print('We have a match')
else:
    print('No match...')

Using finding string in the same string:

if ('stack' in s1) and ('overflow' in s1):
    print('We have a match')
else:
    print('No match...')
if ('stack' in s2) and ('overflow' in s2):
    print('We have a match')
else:
    print('No match...')

In all cases your output should be

We have a match

CodePudding user response:

s="This stack is overflow"
a=["stack","overflow"]

def f(s,a):
    s=s.split(" ")
    n,m=len(s),len(a)
    i=j=0
    while i<n:
        if s[i]==a[j]:
            j =1
            if j==m:
                return True
        i =1
    return False
print(f(s,a)) 
  • Related