Python 如何使用'*',i、 e.';匹配零个或多个';,在带有管道的正则表达式中(或)?

Python 如何使用'*',i、 e.';匹配零个或多个';,在带有管道的正则表达式中(或)?,python,regex,python-3.x,Python,Regex,Python 3.x,我写了这个正则表达式: 重新导入 快速的棕色狐狸跳过了懒惰的狗 myRegex=re.compile( r“(\w |\s)*”#理想情况下,零个或更多(空格字符或单词字符) r“(快速棕色)” ) matches=myRegex.findall(句子) 打印(匹配) 我希望有[('The','quick brown')]打印到屏幕上,这是我理想中想要的,但我得到的是[('quick brown')] 同样,我也尝试将正则表达式更改为: myRegex=re.compile( r“(\w |\

我写了这个正则表达式:

重新导入
快速的棕色狐狸跳过了懒惰的狗
myRegex=re.compile(
r“(\w |\s)*”#理想情况下,零个或更多(空格字符或单词字符)
r“(快速棕色)”
)
matches=myRegex.findall(句子)
打印(匹配)
我希望有
[('The','quick brown')]
打印到屏幕上,这是我理想中想要的,但我得到的是
[('quick brown')]

同样,我也尝试将正则表达式更改为:

myRegex=re.compile(
r“(\w |\s)*)”
r“(快速棕色)”
)

这将导致打印:
[('The','quick brown')]
,这比以前更接近我想要的,但有第二组,这似乎效率低下,因为它只是空格字符

(\w |/s)表示第一个组仅包含一个字符。因此,如果整数与“快速棕色”重新匹配,则第一个组是一个空格,因为第一个括号中只有一个字符。

正确的表达式实际上取决于您尝试执行的操作

  • 是否要在quick brown前面的第一个单词?试试这个:

    sentence = "This is the quick brown fox who jumps over the lazy dog."
    
    myRegex = re.compile(
        r"(\w+)\s*"
        r"(quick brown)"
    )
    
    print(myRegex.findall(sentence))
    
    # Result: [('the', 'quick brown')]
    
    myRegex = re.compile(
        r"(\w+\s*)"
        r"(quick brown)"
    )    
    
    # Output: [('the ', 'quick brown')]
    
    myRegex = re.compile(
        r"([\w\s]+)"
        r"(quick brown)"
    )
    
    # Result: [('This is the ', 'quick brown')]
    
  • 你还想要单词后面的空格吗?试试这个:

    sentence = "This is the quick brown fox who jumps over the lazy dog."
    
    myRegex = re.compile(
        r"(\w+)\s*"
        r"(quick brown)"
    )
    
    print(myRegex.findall(sentence))
    
    # Result: [('the', 'quick brown')]
    
    myRegex = re.compile(
        r"(\w+\s*)"
        r"(quick brown)"
    )    
    
    # Output: [('the ', 'quick brown')]
    
    myRegex = re.compile(
        r"([\w\s]+)"
        r"(quick brown)"
    )
    
    # Result: [('This is the ', 'quick brown')]
    
  • 你想把整组单词放在
    quick brown
    之前吗?试试这个:

    sentence = "This is the quick brown fox who jumps over the lazy dog."
    
    myRegex = re.compile(
        r"(\w+)\s*"
        r"(quick brown)"
    )
    
    print(myRegex.findall(sentence))
    
    # Result: [('the', 'quick brown')]
    
    myRegex = re.compile(
        r"(\w+\s*)"
        r"(quick brown)"
    )    
    
    # Output: [('the ', 'quick brown')]
    
    myRegex = re.compile(
        r"([\w\s]+)"
        r"(quick brown)"
    )
    
    # Result: [('This is the ', 'quick brown')]
    

无论采用哪种方式,此处的
*
标记(零或更多)都不需要用于
\w
,并且在没有匹配单词的情况下,可能会在边缘情况下导致问题。

*
匹配零或更多。Oops。。那是个打字错误-谢谢你让我知道,“([\w\s]*)(快速棕色)”也许吧