我有一个示例文本字符串text_var = 'ndTail7-40512-1',我想在第一次看到一个数字时拆分 - 但我想保留这个数字。目前,我有print(re.split('\d*(?=-)',text_var,1))并且我的输出是['ndTail', '-40512-1']. 但我想保留那个作为触发器的数字,所以它应该看起来像['ndTail', '7-40512-1']. 有什么帮助吗?
1 回答
2
我们可以re.findall在这里尝试使用:
text_var = 'ndTail7-40512-1'
matches = re.findall(r'(.*?)(\d-.*$)', text_var)
print(matches[0])
这打印:
('ndTail', '7-40512-1')
有时它可能更容易使用re.findall而不是re.split.
这里使用的正则表达式模式说:
(.*?) match AND capture all content up to, but including
(\d-.*$) the first digit which is followed by a hyphen;
match and capture this content all the way to the end of the input
请注意,我们使用re.findall的通常有可能返回多个匹配项。但是,在这种情况下,我们的模式匹配到输入的末尾,所以我们只剩下一个包含两个所需捕获组的元组。
于 2020-07-15T17:40:44.877 回答