简体   繁体   English

Python 正则表达式查找在两个标识符之间

[英]Python Regular Expression finding In between two identifiers

I would like to find for few words separated by comma(,) which is not a problem but how do I capture the last of a few words using regular expression?我想找到用逗号(,)分隔的几个单词,这不是问题,但是如何使用正则表达式捕获最后几个单词?

s = "Mr Person 1,Mr Person 2,Mr Person 3,Mr Person 4,Mr Person 5
     Mr Person 6"
m1 = re.findall(r'Mr(.*),', content) #This will get "Person 1,Mr Person 2,Mr Person 3,Mr Person 4"
m2 = re.findall(r'Mr(.*)\s\w+\s((.*).)',content)

Now m2 get all the first line if it has \n(newline at the end) but fails to get anything after the first whitespace of the last comma(,)现在 m2 获取所有第一行,如果它有 \n(末尾的换行符)但在最后一个逗号(,)的第一个空格之后没有得到任何东西
What I want is to get all "Mr Person" from string => "AB C Mr Person 1, Mr person 2, ..., Mr Last person XYZ"我想要的是从字符串中获取所有“Mr Person”=>“AB C Mr Person 1, Mr person 2, ..., Mr Last person XYZ”

Assuming you have a string with either , or a newline as separator, the best is not to try to match the content, but to split:假设您有一个带有 或换行符作为分隔符的字符串,最好不要尝试匹配内容,而是拆分:

s = """Mr Person 1,Mr Person 2,Mr Person 3,Mr Person 4,Mr Person 5
     Mr Person 6"""
    
import re
l = re.split(r'[,\n]\s*', s)

output: output:

['Mr Person 1',
 'Mr Person 2',
 'Mr Person 3',
 'Mr Person 4',
 'Mr Person 5',
 'Mr Person 6']

If really you only have , , just use the string split method:如果你真的只有, ,只需使用字符串split方法:

l = s.split(',')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM