簡體   English   中英

如何讓正則表達式在某事之前獲取單詞,但不獲取該單詞后面的模式背后的所有內容?

[英]How do I make a regex take the word before something but not grab everything that is behind the pattern that follows the word?

import re, random

input_t = str(input())
input_text_to_check = input_text.lower()

regex_pattern_01 = r"\s*\¿?(?:how many|how much)\s*((?:\w+\s*)+)?\s*\¿?(?:is there|are there|is in|are in|does he have|does she have|do you have|do we have| am | is | are |\?)\s*"

n = re.search(regex_pattern_01, input_text_to_check, re.IGNORECASE)

if n:
    accounting_object, = n.groups()
    accounting_object = accounting_object.strip()

    if(accounting_object == ' ' or accounting_object == ''):
        print("I think you haven't told me what you mean")

    print(accounting_object)

我需要在字符串中提取“名詞及其形容詞以防萬一”。 例如,例如在這些情況下,這應該提取以下單詞:

有多少牛奶? --->'牛奶'

袋子里有多少種子? ---> '種子'

閣樓里有幾把古董木椅? ---> '古董木椅'

他有多少個 1 米尺? ---> '1 米尺'

需要多少個堅果? ---> '堅果'

多少個舊時鍾--->它沒有進入if

有多少個舊時鍾 ---> 它確實輸入了 if,並給出“舊時鍾”

有多少個舊鍾? --->它確實進入了if,並給出'舊時鍾'

我應該如何修復這個正則表達式? 因為它給了我回報,例如:'古董木椅在閣樓里'而不是'古董木椅'

為什么你不為每種情況寫幾個條件,例如在這種情況下, How manyare

import re
x = 'How many antique wooden chairs are in the attic?'
p = re.compile(r'How many\s*(.*)are')
m = p.search(x)           # Run a regex search anywhere inside a string
if m:                     # If there is a match
    print(m.group(1))     # Print Group 1 value

Output 將

antique wooden chairs

您在其中查找名詞的組 ( (?:\w+\s*)+ ) 是“貪婪的”。 它嘗試盡可能多地匹配,從而消耗句子的 rest。 您可以通過添加? +之后。

我假設您還想讓最后一個空格不貪心,這樣它就不會在名詞之后捕獲空格。 那么它將是: (?:\w+\s*?)+? .

這里玩正則表達式。

暫無
暫無

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

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