簡體   English   中英

Python Regex:匹配短語,而不考慮中間空格

[英]Python Regex: Matching a phrase regardless of intermediate spaces

給定行中的短語,即使單詞在行中具有不同數量的空格,我也必須能夠匹配該短語。

因此,如果該短語是"the quick brown fox" ,而行是"the quick brown fox jumped over the lazy dog" ,則仍應匹配"the quick brown fox"的實例。

我已經嘗試過的方法是用正則表達式模式將行中的所有空白實例替換為空白,但是,如果該行包含的字符不被正則表達式視為文字,則這種方法並不總是有效。

這應該工作:

import re

pattern = r'the\s+quick\s+brown\s+fox'
text = 'the           quick      brown        fox jumped over the lazy dog'

match = re.match(pattern, text)
print(match.group(0))

輸出為:

the           quick      brown        fox

您可以使用此正則表達式。 在這里檢查

(the\s+quick\s+brown\s+fox)

您可以用空格將給定的字符串分割,再用空格將它們重新連接起來,以便隨后將其與您要查找的短語進行比較:

s = "the           quick      brown        fox"
' '.join(s.split()) == "the quick brown fox" # returns True

對於一般情況:

  1. 用一個空格字符替換每個空格字符序列。
  2. 檢查給定的句子是否是替換后的行的子字符串

     import re pattern = "your pattern" for line in lines: line_without_spaces= re.sub(r'\\s+', ' ', line) # will replace multiple spaces with one space return pattern in line_without_spaces 

正如您稍后所闡明的,您需要匹配單詞的任何行和系列。 為了達到這個目的,我添加了更多示例來闡明兩個提議的類似正則表達式的作用:

text = """the           quick      brown        fox
another line                    with single and multiple            spaces
some     other       instance     with        six                      words"""

匹配整條線

第一個匹配整行,迭代單行

pattern1 = re.compile(r'((?:\w+)(?:\s+|$))+')
for i, line in enumerate(text.split('\n')):
    match = re.match(pattern1, line)
    print(i, match.group(0))

其輸出為:

0 the           quick      brown        fox
1 another line                    with single and multiple            spaces
2 some     other       instance     with        six                      words

匹配整條線

第二個匹配單個單詞,並在單個行上迭代時一個接一個地迭代它們:

pattern2 = re.compile(r'(\w+)(?:\s+|$)')
for i, line in enumerate(text.split('\n')):
    for m in re.finditer(pattern2, line):
        print(m.group(1))
    print()

其輸出為:

the
quick
brown
fox

another
line
with
single
and
multiple
spaces

some
other
instance
with
six
words

暫無
暫無

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

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