我有多个regEx模式,我希望在文本中匹配它们以在它们周围添加空格..
import re
regList = [r'(#\w+)',r'\d{1,}\.\d{1,}']
# for Hashtags , decimal_numbers
str = '22.21@122122.# #fdsf21.ddcf'
for reg in regList:
s = re.sub(reg, r' \1 ', str)
str = s
print(str)
当我明确地调用regList的一个项目时:
s = re.sub(regList[0], r' \1 ', str)
代码正常运行,否则会出现错误:
22.21@122122.# #fdsf21 .ddcf
Traceback (most recent call last):
File "C:\Python35\lib\sre_parse.py", line 938, in expand_template
literals[index] = g(group) or empty
IndexError: no such group
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "D:/OneDrive/PhD/Tasks & activities/Courses/computational liguistic/P1/py_File/ssssssssssssssssssssss.py", line 8, in <module>
s = re.sub(reg, r' \1 ', str)
File "C:\Python35\lib\re.py", line 182, in sub
return _compile(pattern, flags).sub(repl, string, count)
File "C:\Python35\lib\re.py", line 330, in filter
return sre_parse.expand_template(template, match)
File "C:\Python35\lib\sre_parse.py", line 940, in expand_template
raise error("invalid group reference")
sre_constants.error: invalid group reference