簡體   English   中英

在字符串中的部分查找 substring

[英]Find a substring in parts within a string

我正在學習 Python,遇到了一種情況,我必須在字符串中但部分地找到 substring。

例如,我的字符串可以是 My string="this is stack overflow" 或 My string="this stack is overflow"

而且我必須找出是否存在堆棧溢出。

順序必須相同,但可以在堆棧和溢出這兩個部分之間寫入任何內容。

任何幫助表示贊賞。!

使用正則表達式,代碼如下

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'>

您可以通過多種方式執行此操作。 我能想到的兩個是:

  1. 常用表達
  2. 在同一個字符串中查找兩個字符串。
s1 = "this is stack overflow"
s2 = "this stack is overflow"

使用正則表達式,您可以這樣做:

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...')

在同一字符串中使用查找字符串:

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...')

在所有情況下,您的 output 應該是

We have a match
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)) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM