如何使用Python 3.5在多行上使用正则表达式?
如果我有以下几点如何使用Python 3.5在多行上使用正则表达式?,python,regex,Python,Regex,如果我有以下几点 string = '''This is a multiline string for example purposes more stuff''' 我想用正则表达式只找到中间的两行,我该怎么做?您可以使用*捕获一整行减去换行符,然后使用\n捕获换行符。例如: import re string = '''This is a multiline string for example purposes more stuff'''
string = '''This is a
multiline string
for example purposes
more stuff'''
我想用正则表达式只找到中间的两行,我该怎么做?您可以使用
*
捕获一整行减去换行符,然后使用\n
捕获换行符。例如:
import re
string = '''This is a
multiline string
for example purposes
more stuff'''
r = re.search('^.*\n(.*)\n(.*)\n.*$', string)
print r.group(0) # Whole match
print r.group(1) # Second line
print r.group(2) # Third line
但是,在本例中,将字符串拆分为一个行数组更有意义
print string.split('\n')[1] # Prints the second line
通常,如果要在具有多行的字符串上搜索
regex
的匹配项,即它包括\n
,则使用多行修饰符
re.compile(r'',re.MULTILINE)
您是指第二行和第三行,还是指第一行和最后一行之间的所有行?难道你不能分成几行,然后得到你需要的吗?所以这里不是为你从头开始写代码的。你应该先尝试解决你的问题,然后回来问一个具体的问题,如果你的解决方案不起作用。