Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/flutter/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex 与之间的Python正则表达式匹配字符串\n|_Regex_Python 2.7 - Fatal编程技术网

Regex 与之间的Python正则表达式匹配字符串\n|

Regex 与之间的Python正则表达式匹配字符串\n|,regex,python-2.7,Regex,Python 2.7,我有一篇文章里面有很多\n和|。 以下是一个示例: this is a sample\n text. This symbol | shows what I am talking about. This is \n another | sample 我希望能够提取\n和|之间的所有内容。对于上面的示例,这是:text。此符号以及另一个符号 在Python2.7中如何实现这一点 使用捕获组 re.findall(r'\n([^|]*)\|', string) [^ |]*匹配任何字符,但不匹配符

我有一篇文章里面有很多
\n
|
。 以下是一个示例:

this is a sample\n text. This symbol | shows what I am talking about.
This is \n another | sample
我希望能够提取
\n
|
之间的所有内容。对于上面的示例,这是:
text。此符号
以及另一个符号 在Python2.7中如何实现这一点

使用捕获组

re.findall(r'\n([^|]*)\|', string)
[^ |]*
匹配任何字符,但不匹配
符号,零次或多次。默认情况下,
re.findall
打印捕获组中存在的字符。所以它会打印出中间的字符
|
是正则表达式中的一个特殊元字符,其作用类似于交替运算符。要匹配文字符号,必须在正则表达式中对其进行转义。

您可以使用:

s='this is a sample\n text. This symbol | shows what I am talking about.\nThis is \n another | sample'

>>> print re.findall(r'\n([^|\n]*)\|', s);
[' text. This symbol ', ' another ']
此正则表达式捕获文本
\n
,后跟一个否定模式,表示:

([^ |\n]*)
,表示匹配0个或多个非管道或换行符的字符。方括号用于将其捕获到组中,稍后将在
findall
输出中打印。它最后匹配一个文本
|

或者使用lookaheads:

>>> print re.findall(r'(?<=\n )[^|\n]*(?= +\|)', s);
['text. This symbol', 'another']

>>print re.findall(r'(
\n
是文字字符还是换行字符?谢谢阿维纳什。你能解释一下它是如何工作的吗?实际上这给了
re.findall(r'\n([^ |]*)\\\\\\','abc\n foo\n bar\n baz | 123')
错误的结果,即
['foo\n bar\n baz']
而不是
['baz']
感谢您的精彩解释。