簡體   English   中英

Python正則表達式:如何將數字與非數字匹配?

[英]Python regex: How to match a number with a non-number?

我希望拆分號碼與另一個角色。

輸入:

we spend 100year

輸出:

we speed 100 year

輸入:

today i'm200 pound

產量

today i'm 200 pound

輸入:

he maybe have212cm

輸出:

he maybe have 212 cm

我試過re.sub(r'(?<=\\S)\\d', ' \\d', string)re.sub(r'\\d(?=\\S)', '\\d ', string) ,這不起作用。

這樣做:

ins='''\
we spend 100year
today i'm200 pound
he maybe have212cm'''

for line in ins.splitlines():
    line=re.sub(r'\s*(\d+)\s*',r' \1 ', line)
    print line

打印:

we spend 100 year
today i'm 200 pound
he maybe have 212 cm

同一行文本中多個匹配項的語法相同:

>>> re.sub(r'\s*(\d+)\s*',r' \1 ', "we spend 100year + today i'm200 pound")
"we spend 100 year + today i'm 200 pound"

捕獲組(通常)從左到右編號, \\number表示匹配中的每個編號組:

>>> re.sub(r'(\d)(\d)(\d)',r'\2\3\1','567')
'675'

如果它更容易閱讀,您可以命名您的捕獲組而不是使用\\1 \\2表示法:

>>> line="we spend 100year today i'm200 pound"
>>> re.sub(r'\s*(?P<nums>\d+)\s*',r' \g<nums> ',line)
"we spend 100 year today i'm 200 pound"

這照顧一種情況:

>>> re.sub(r'([a-zA-Z])(?=\d)',r'\1 ',s)
'he maybe have 212cm'

這會照顧到另一個:

>>> re.sub(r'(?<=\d)([a-zA-Z])',r' \1',s)
'he maybe have212 cm'

希望比我有更多正則表達式經驗的人可以弄清楚如何將它們組合在一起...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM