簡體   English   中英

如何使用 python 中的正則表達式匹配一句話中的模式?

[英]How to match patterns in one sentence using regex in python?

這里有2個例子,

1. I need to take this apple. I just finished the first one.

2. I need to get some sleep. apple is not working.

我想在同一個句子中將文本與needapple匹配。 通過使用need.*apple它將匹配兩個示例。 但我希望它只適用於第一個。 如何更改代碼,或者我們在 Python 中有其他字符串方法嗎?

@ctwheels 發表的關於拆分的評論. 然后測試它是否包含appleneed是一個不需要使用正則表達式的好方法。 但是,我首先會在空白處再次拆分,然后根據結果列表測試這些單詞,以確保您與applesauce不匹配。 但這是一個正則表達式解決方案:

import re

text = """I need to take this apple. I just finished the first one.
I need to get some sleep. apple is not working."""

regex = re.compile(r"""
    [^.]*           # match 0 or more non-period characters
    (
        \bneed\b    # match 'need' on a word boundary
        [^.]*       # match 0 or more non-period characters
        \bapple\b   # match 'apple' on a word boundary
      |             # or
        \bapple\b   # match 'apple' on a word boundary
        [^.]*       # match 0 or more non-period characters
        \bneed\b    # match 'need' on a word boundary
    )
    [^.]*           # match 0 or more non-period characters
    \.              # match a period
    """, flags=re.VERBOSE)

for m in regex.finditer(text):
    print(m.group(0))

印刷:

I need to take this apple.

這兩種解決方案的問題是,如果句子中包含一個句號,其使用目的不是結束一個句子,例如I need to take John Q. Public's apple. 在這種情況下,您需要一種更強大的機制來將文本分成句子。 然后,對這些句子進行操作的正則表達式當然會變得更簡單,但在空白處拆分似乎仍然是最有意義的。

暫無
暫無

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

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