簡體   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