2024-04-26 21:16:16 发布
网友
我需要两个regex操作的帮助。
例如,“太酷了(234)”=>;“太酷了”
直到帕伦:regex = re.compile("(.*?)\s*\(")
regex = re.compile("(.*?)\s*\(")
在第一组parens中:regex = re.compile(".*?\((.*?)\)")
regex = re.compile(".*?\((.*?)\)")
编辑:单个regex版本:regex = re.compile("(.*?)\s*\((.*?)\)")
regex = re.compile("(.*?)\s*\((.*?)\)")
示例输出:
>>> import re >>> r1 = re.compile("(.*?)\s*\(") >>> r2 = re.compile(".*?\((.*?)\)") >>> text = "this is so cool (234)" >>> m1 = r1.match(text) >>> m1.group(1) 'this is so cool' >>> m2 = r2.match(text) >>> m2.group(1) '234' >>> r3 = re.compile("(.*?)\s*\((.*?)\)") >>> m3 = r3.match(text) >>> m3.group(1) 'this is so cool' >>> m3.group(2) '234' >>>
当然要注意,这对于多组paren是行不通的,因为它只需要一个带括号的文本块(根据您的示例)。任意递归的开闭parens匹配语言是不规则的。
不需要正则表达式。
>>> s="this is so cool (234)" >>> s.split("(")[0] 'this is so cool ' >>> s="this is so cool (234) test (123)" >>> for i in s.split(")"): ... if "(" in i: ... print i.split("(")[-1] ... 234 123
听起来你可以这么做:
re.findall('[^()]+', mystring)
拆分也可以:
re.split('[()]', mystring)
无论哪种方式,第一个括号前的文本都将是结果数组中的第一项,第一组parens中的文本将是第二项。
直到帕伦:
regex = re.compile("(.*?)\s*\(")
在第一组parens中:
regex = re.compile(".*?\((.*?)\)")
编辑:单个regex版本:
regex = re.compile("(.*?)\s*\((.*?)\)")
示例输出:
当然要注意,这对于多组paren是行不通的,因为它只需要一个带括号的文本块(根据您的示例)。任意递归的开闭parens匹配语言是不规则的。
不需要正则表达式。
听起来你可以这么做:
拆分也可以:
无论哪种方式,第一个括号前的文本都将是结果数组中的第一项,第一组parens中的文本将是第二项。
相关问题 更多 >
编程相关推荐