繁体   English   中英

如何正则表达式的开头和结尾 - python

[英]How to regex the beginning and the end of a sentence - python

我有一个包含日期、国家和城市的字符串列表:

myList = ["(1922, May, 22; USA; CHICAGO)","(1934, June, 15; USA; BOSTON)"]

我只想提取日期和城市(城市总是用大写字母)。 到目前为止,我有这个:

for info in myList:

        pattern_i = re.compile(r"[^;]+")
        pattern_f = re.compile(r";\s\b([A-Z]+)\)")

        mi = re.match(pattern_i, info)
        mf = re.match(pattern_f, info)

        print(mi)
        print(mf)

我正进入(状态:

<re.Match object; span=(0, 14), match='(1922, May, 22'>
None
<re.Match object; span=(0, 15), match='(1934, June, 15'>
None

我已经尝试了很多东西,但似乎无法找到解决方案。 我在这里想念什么?

正则表达式对于具有简单、一致格式的数据来说太过分了。 这可以使用内置的字符串操作函数轻松完成。

for entry in myList:
    date, country, city = [x.strip() for x in entry[1:-1].split(';')]

# Explanation
entry[1:-1] # Strip off the parenthesis
entry[1:-1].split(';') # Split into a list of strings using the ';' character
x.strip() # Strip extra whitespace

日期的正则表达式: ^\(([^;]+)

城市的正则表达式([AZ]+)\)$

您可以使用pandas

p='\((?P<date>.*);.*;(?P<city>.*)\)'

pd.Series(myList).str.extract(p)

Output:

             date      city
0   1922, May, 22   CHICAGO
1  1934, June, 15    BOSTON
 thanks, But I am still curious? why am I getting None for mf?

Python 基于正则表达式提供两种不同的原始操作:re.match() 仅在字符串的开头检查匹配,而 re.search() 在字符串中的任何位置检查匹配(这是 Perl 默认执行的操作)。Ref DOcs


re.match在字符串的开头搜索匹配,因为您尝试匹配的模式不在字符串的开头,所以您得到None您可以使用re.search是在任何地方查找匹配值的一种选择字符串


正如我建议 split 在这里是一个更好的选择,你应该拆分; 并取第一个和最后一个元素以获得所需的 output

暂无
暂无

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

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