python - 正则匹配重复字符串中某一段内容
黄舟
黄舟 2017-04-17 15:53:10
0
2
393

有这么一个字符串

s = 'PN:\nabcd\nPN:\nabcd\nabcd\nPN:\nabcd\nabcd\n'
即
s = '''
    PN:
    abcd
    PN:
    abcd
    abcd
    PN:
    abcd
    abcd
    '''

我只想匹配到其中两个PN之间的\nabcd\n或者\nabcd\nabcd\n,然后我用了如下正则:

result = re.search('P\s*N:\s*(.*[\s\S]*)P.*', s, re.IGNORECASE).group(0)

最后输出result的结果为:

PN:
abcd
PN:
abcd
abcd
PN:

求大神指点~

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(2)
左手右手慢动作

Well, the problem has been solved, just don’t use regular expressions...
Sure enough, I was misled by myself because I relied too much on regular expressions.
Attached code:

lst = s1.split('PN')
for index, each in enumerate(lst):
    print index, ' + ', each

Output result:

0  +  
1  +  : 
    abcd
2  +  : 
    abcd
    abcd 
3  +  : 
    abcd
    abcd

Then you only need to write a function and pass in parameters from the outside to get the content between any two PNs...

巴扎黑

I don’t understand python, so I wrote js, I don’t know if it will help

var str = 'PN:\nabcd\nPN:\nabcd\nabcd\nPN:\nabcd\nabcd\n';
var result = str.match(/PN:([a-z\n])*[^PN:]+/ig);

Results

["PN:\nabcd\n", "PN:\nabcd\nabcd\n", "PN:\nabcd\nabcd\n"]
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!