用于在python中循环时匹配字母表、数字和特殊特许权的正则表达式

2024-06-26 14:37:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图找到文字和打印使用下面的代码。一切都很完美,但唯一的问题是我无法打印最后一个字(即数字)

words = ['Town of','Block No.','Lot No.','Premium (if any) Paid ']

import re
for i in words:
    y = re.findall('{} ([^ ]*)'.format(i), textfile)
    print(y)

我正在使用的文本文件:

textfile = """1, REBECCA M. ROTH , COLLECTOR OF TAXES of the taxing district of the
township of MORRIS for Six Hundred Sixty Seven dollars andFifty Two cents, the land
in said taxing district described as Block No. 10303 Lot No. 10 :
and known as 239 E HANOVER AVE , on the tax Taxes For: 2012
Sewer

Assessments For Improvements

Total Cost of Sale 35.00
Total
Premium (if any) Paid 1,400.00 """

我想知道我在哪里犯了错误。 如有任何建议,我们将不胜感激


Tags: ofthenoinreforifany
2条回答

两个问题:

  1. 当前的'Premium (if any) Paid '字符串以空格结尾,并且'{} ([^ ]*)'{}之后还有一个空格,这将它们相加。删除'Premium (if any) Paid '中的尾随空格
  2. 需要对括号进行转义,因此如果希望保持正则表达式不变,列表中的字符串应为['Premium \(if any\) Paid']。您也可以改用re.escape

对于您的特殊情况,这似乎是一个最佳解决方案:

words = ['Town of','Block No.','Lot No.','Premium (if any) Paid']

import re
for i in words:
    y = re.findall('{}\s+([\S]*)'.format(re.escape(i)), text, re.I)
    print(y)

有几个问题:

  1. 正如其他人提到的,您需要转义特殊字符,如括号({}和点.。非常简单,您可以使用^{}
  2. 另一个问题是Premium \(if any\) Paid 中的尾随空格(它试图匹配两个空格,而不是一个,因为您也在检查正则表达式{} ([^ ]*)中的空格)

您应该改为将代码更改为以下内容:

See working code here

words = ['Town of','Block No.','Lot No.','Premium (if any) Paid']

import re
for i in words:
    y = re.findall('{} ([^ ]*)'.format(re.escape(i)), textfile)
    print(y)

相关问题 更多 >