python - 使用正则表达式和 python 3 在字符串中查找模式

标签 python regex algorithm python-3.x

我有如下字符串

string = "your invoice number IVR/20170531/XVII/V/12652967 and IVR/20170531/XVII/V/13652967"

我想使用具有此模式的正则表达式将发票编号 IVR/20170531/XVII/V/12652967 和 IVR/20170531/XVII/V/13652967 放入列表中

       result = re.findall(r'INV[/]\d{8}[/](M{1,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})|M{0,4}(CM|C?D|D?C{1,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})|M{0,4}(CM|CD|D?C{0,3})(XC|X?L|L?X{1,3})(IX|IV|V?I{0,3})|M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|I?V|V?I{1,3}))[/](M{1,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})|M{0,4}(CM|C?D|D?C{1,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})|M{0,4}(CM|CD|D?C{0,3})(XC|X?L|L?X{1,3})(IX|IV|V?I{0,3})|M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|I?V|V?I{1,3}))[/]\d{7,9}',string)  

但是结果是

[('XVII',  '', '','',  '', '',  '',  '', 'X',  'VII', '',  '', '',  'V','','','',  '', '',  '', '',  '', '',  '', '',  'V')]

我在 http://regexr.com/ 中尝试过这种模式,结果是适当的,但在 python 中不是

最佳答案

您应该修改您的模式,在整个正则表达式周围添加普通括号,然后使用第一个反向引用访问该文本。您可以阅读有关反向引用的更多信息 here .

invoices = []
# Your pattern was slightly incorrect
pattern = re.compile(r'IVR[/]\d{8}[/](M{1,4}(CM|CD|D?C{0,3})|(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})|M{0,4}(CM|C?D|D?C{1,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})|M{0,4}(CM|CD|D?C{0,3})(XC|X?L|L?X{1,3})(IX|IV|V?I{0,3})|M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|I?V|V?I{1,3}))[/](M{1,4}(CM|CD|D?C{0,3})|(XC|XL|L?X{0,3})|(IX|IV|V?I{0,3})|M{0,4}(CM|C?D|D?C{1,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})|M{0,4}(CM|CD|D?C{0,3})(XC|X?L|L?X{1,3})(IX|IV|V?I{0,3})|M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|I?V|V?I{1,3}))[/]\d{7,9}') 

# For each invoice pattern you find in string, append it to list
for invoice in pattern.finditer(string):
    invoices.append(invoice.group(1))

注意:

您还应该使用 pattern.finditter(),因为这样您就可以遍历名为 string 的文本中的所有模式发现。来自 re.finditer 文档:

re.finditer(pattern, string, flags=0) Return an iterator yielding MatchObject instances over all non-overlapping matches for the RE pattern in string. The string is scanned left-to-right, and matches are returned in the order found. Empty matches are included in the result unless they touch the beginning of another match.

关于python - 使用正则表达式和 python 3 在字符串中查找模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44665849/

相关文章:

algorithm - 除前 K 和后 K 个元素外的排序数组

python - 如何并发多次运行相同的异步函数?

python - 如何将我的 python spyder 与 github 连接?

regex - 在带有括号的一维列表上应用递归

algorithm - 在不到指数时间内进行模糊匹配重复数据删除?

c++ - 用 C++ 设计 map

python - 在被调用函数和调用函数之间共享 Python 范围

python - 使用pytorch构建多线性,但得到的结果不是我想要的?

java - 使用正则表达式查找具有特殊字符的字符串

java - 对捕获组的主题感到困惑吗?