我有以下regexp (使用Python语法):
(\d+)x(\d+)(?:\s+)?-(?:\s+)?([^\(\)]+)(?:\s+)?\((\d+)(?:(?:\s+)?-(?:\s+)?([^\(\)]+))?\)(?:(?:\s+)?\(([^\(\)]+)\))?(?:(?:\s+)?-(?:\s+)?([^\(\)]+) \((\d+)\))?它匹配符合以下形式之一的字符串:
21x04 - Some Text (04)
6x03 - Some Text (00 - Some Text)
6x03 - Some Text (00 - Some Text) (Some Text)
23x01 - Some Text (10) - Some Text (02)数字和文本会有所不同,并被捕获。但是,间距并不总是一致的,因此它被设计为允许任意数量的空间。
有没有一种简化它的方法--我并不是一定要找人帮我做这件事,只是告诉我有没有工具(谷歌搜索得到了一些结果,但它们都不能处理它),或者是一种系统的方法来做这件事。
或者,有没有人能看到更好的正则表达式来满足这种情况?
发布于 2015-04-09 06:54:49
您可以放弃一些可选的非捕获组,例如,您可以更改以下内容:
(\d+)x(\d+)(?:\s+)?-(?:\s+)?([^\(\)]+)(?:\s+)?\((\d+)(?:(?:\s+)?-(?:\s+)?([^\(\)]+))?\)(?:(?:\s+)?\(([^\(\)]+)\))?(?:(?:\s+)?-(?:\s+)?([^\(\)]+) \((\d+)\))?要这样做:
(\d+)x(\d+)\W+([^()]+)\D+\((\d+)(?:\W*-\W*([^()]+))?\)(?:\W*\(([^()]+)\))?(?:\W*-\W*([^()]+) \((\d+)\))?我可以用\W*替换一些(?:\s+)?,而且您也不必在字符类[^\(\)]中转义括号,您可以使用[^()]
顺便说一句,你也可以测试这个正则表达式,它可能对你有用:
(\d+)x(\d+)|-\s*([\w\s]+)|(\w+)发布于 2015-04-09 07:57:27
为了简化问题,请考虑将其分为两部分: 1.获取字符串(可以包含数字或字母)和2.当字符串包含数字时获取数字:
data = '''21x04 - Some Text (04)
6x03 - Some Text (00 - Some Text)
6x03 - Some Text (00 - Some Text) (Some Text)
23x01 - Some Text (10) - Some Text (02)'''
import re
# the regex to extract your data as strings
aaa = re.compile('[\w\s]+')
# the regex to extract the numbers from the strings
nnn = re.compile('\d+')
for line in data.split('\n'):
matches = aaa.findall(line)
groups = []
for m in matches:
m = m.strip()
n = nnn.findall(m)
if m != '':
groups.extend([m] if n == [] else n)
print(groups)
# ['21', '04', 'Some Text', '04']
# ['6', '03', 'Some Text', '00', 'Some Text']
# ['6', '03', 'Some Text', '00', 'Some Text', 'Some Text']
# ['23', '01', 'Some Text', '10', 'Some Text', '02']https://stackoverflow.com/questions/29526482
复制相似问题