![](/img/trans.png)
[英]Regex to match comma-separated strings containing comma-formatted decimals
[英]Python regex for capturing comma-separated strings conditionally
我有一個可以有 3 種不同樣式的人名列表:
{last name}, {first name} {middle name}
(例如:Bob、Dylan Tina){last name}, {first name} {middle initial}.
(例如:Bob、Dylan T.){last name}, {first name}
(例如:Bob、Dylan)這是我寫的正則表達式:
^[a-zA-Z]+(([' ,.-][a-zA-Z ])?[a-zA-Z]*)*$
但它不起作用。
你應該使用這個正則表達式:
(\w+),\s*(\w+)\s*(\w{0,}\.*)
這是你會得到的結果:
>>> import re
>>> s1 = "Bob, Dylan Tina"
>>> s2 = "Bob, Dylan"
>>> s3 = "Bob, Dylan T."
>>> p = re.compile(r"(\w+),\s*(\w+)\s*(\w{0,}\.*)")
>>> re.findall(p, s1)
[('Bob', 'Dylan', 'Tina')]
>>> re.findall(p, s2)
[('Bob', 'Dylan', '')]
>>> re.findall(p, s3)
[('Bob', 'Dylan', 'T.')]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.