【发布时间】:2016-11-03 00:39:08
【问题描述】:
[从我的旧 question 跟进,提供更好的描述和链接]
尝试匹配两个符号之间的任何字符(包括换行符、制表符、空格等),包括那些符号。
例如:
foobar89\n\nfoo\tbar; '''废话废话'8&^"'''
需要匹配
''废话废话'8&^"'''
和
fjfdaslfdj; '''废话\n废话\n\t\t废话\n'8&^"'''
需要匹配
'''废话\n废话\n\t\t废话\n'8&^"'''
我正在测试正则表达式的 Python 代码(取自并改编自 here):
import collections
import re
Token = collections.namedtuple('Token', ['typ', 'value', 'line', 'column'])
def tokenize(code):
token_specification = [
('BOTH', r'([\'"]{3}).*?\2'), # for both triple-single quotes and triple-double quotes
('SINGLE', r"('''.*?''')"), # triple-single quotes
('DOUBLE', r'(""".*?""")'), # triple-double quotes
# regexes which match OK
('COM', r'#.*'),
('NEWLINE', r'\n'), # Line endings
('SKIP', r'[ \t]+'), # Skip over spaces and tabs
('MISMATCH',r'.'), # Any other character
]
test_regexes = ['COM', 'BOTH', 'SINGLE', 'DOUBLE']
tok_regex = '|'.join('(?P<%s>%s)' % pair for pair in token_specification)
line_num = 1
line_start = 0
for mo in re.finditer(tok_regex, code):
kind = mo.lastgroup
value = mo.group(kind)
if kind == 'NEWLINE':
line_start = mo.end()
line_num += 1
elif kind == 'SKIP':
pass
elif kind == 'MISMATCH':
pass
else:
if kind in test_regexes:
print(kind, value)
column = mo.start() - line_start
yield Token(kind, value, line_num, column)
f = r'C:\path_to_python_file_with_examples_to_match'
with open(f) as sfile:
content = sfile.read()
for t in tokenize(content):
pass #print(t)
file_with_examples_to_match 在哪里:
import csv, urllib
class Q():
"""
This class holds lhghdhdf hgh dhghd hdfh ghd fh.
"""
def __init__(self, l, lo, d, m):
self.l= l
self.lo= longitude
self.depth = d
self.m= m
def __str__(self):
# sdasda fad fhs ghf dfh
d= self.d
if d== -1:
d= 'unknown'
m= self.m
if m== -1:
d= 'unknown'
return (m, d, self.l, self.lo)
foobar89foobar; '''blah qsdkfjqsv,;sv
vqùlvnqùv
dqvnq
vq
v
blah blah'8&^"'''
fjfdaslfdj; '''blah blah
blah
'8&^"'''
从this answer 开始,我尝试r"('''.*?''')|"r'(""".*?""") 匹配三个单引号和三个双引号的情况,但均未成功。尝试r'([\'"]{3}).*?\2') 时相同。
我已经设置了一个 online 正则表达式测试器,其中一些正则表达式确实匹配,但在上面的代码中它们失败了。
我有兴趣了解 Python 的正则表达式,因此我希望能得到一个解决方案(也许是一个有效的正则表达式来对我的代码进行所需的匹配)和一个简短的解释,以便我能看到我的缺点。
【问题讨论】:
-
我想我无法理解您在寻找什么。由于 python 正则表达式的贪婪性质,'.*' 应该捕获两个撇号之间的任何内容,包括任何撇号。究竟是什么问题?
-
@JasonBray 问题是我试图匹配 3 个连续双引号或 3 个连续单引号之间的任何内容。当我使用正则表达式
r"('''.*?''')"、r'(""".*?""")'、r'([\'"]{3}).*?\2')时,即使在线正则表达式测试人员显示这些正则表达式确实匹配,但当它们在我的描述中的代码中使用时,它们不匹配。寻找理解原因。
标签: python regex python-3.x quotes