简体   繁体   English

使用正则表达式匹配python中用空格包围的括号

[英]Match parenthesis surrounded by spaces in python with regex

Why doesn't the following code block match the parantheses? 为什么下面的代码块不匹配括号?

In [27]: import re

In [28]: re.match('.*?([\(]*)', '  (((( ' ).groups()
Out[28]: ('',)

Demonstrating my comment: 展示我的评论:

import re
>>> re.match('.*?([\(]*)', '   (((( ' ).groups()
('',)
>>> re.match('.*?([\(]+)', '   (((( ' ).groups()
('((((',)
>>> 

Note - you don't even need the backslash inside the [] - since special characters lose their meaning. 注意-您甚至不需要在[]使用反斜杠-因为特殊字符会失去其含义。 So 所以

>>> re.match('.*?([(]+)', '   (((( ' ).groups()
('((((',)
>>> 

works too... 也可以...

This is because your "non greedy" first quantifier ( *? ) doesn't need to give anything to the second quantifier - since the second quantifier is happy with zero matches. 这是因为您的“非贪婪”第一个量词( *? )不需要为第二个量词提供任何内容-因为第二个量词对零匹配感到满意。

In your case .*? 就您而言.*? means everything because you used [\\(]* which means 0 or more. So changing * into + will work for you as + means 1 or more. 表示所有内容,因为您使用了[\\(]*表示0或更大。因此将*更改为+将为您工作,因为+表示1或更大。

re.match('.*?([\(]+)', '  (((( ' ).groups()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python正则表达式匹配括号,但不嵌套括号 - Python Regex match parenthesis but not nested parenthesis Python正则表达式:在字符和字母周围插入空格,不包含空格 - Python regex: insert spaces around characters and letters NOT surrounded by spaces python regex:匹配一个正好2个字符包围的字符 - python regex: match a char surrounded by exactly 2 chars Python检测由空格包围的字符 - Python detect character surrounded by spaces 使用 python 删除管道、空格、括号但不删除引号的正则表达式 - Regex expression for removing pipe, spaces, parenthesis, but not quotes using python Python 重新正则表达式子字母未用引号括起来,如果它们匹配特定单词,包括正则表达式组/匹配,则不 - Python re regex sub letters not surrounded in quotes and not if they match specific word including regex group / match python替换没有空格的正则表达式匹配 - python replace regex match without spaces 不要将单词边界beetwen括号与python正则表达式匹配 - Do not match word boundary beetwen parenthesis with python regex 如何使用 Python 正则表达式匹配最里面的括号集? - How to match the innermost parenthesis set using Python regex? Python 正则表达式匹配任何括在引号括号大括号或括号中的内容 - Python regex match anything enclosed in either quotations brackets braces or parenthesis
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM