簡體   English   中英

如果用數字而不是字母包圍,Python正則表達式將替換字符串中的空格

[英]Python regex replace space from string if surrounded by numbers, but not letters

我的輸入變量為字符串:

'12345 67890'
'abc 123'
'123 abc'
'abc def'

我的目的是如果兩側的字符都是數字而不是字母,則刪除字符之間的空格。 我正在考慮使用re模塊,也許是re.sub()函數或類似的東西。

所需的輸出:

'1234567890'
'abc 123'
'123 abc'
'abc def'

謝謝

regex和后向使用regex

>>> import re
>>> re.sub(r'(?<=\d)\s(?=\d)', '', '12345 67890')
'1234567890'
>>> re.sub(r'(?<=\d)\s(?=\d)', '', 'abc 123')
'abc 123'
>>> re.sub(r'(?<=\d)\s(?=\d)', '', '123 abc')
'123 abc'
>>> re.sub(r'(?<=\d)\s(?=\d)', '', 'abc def')
'abc def'
>>> re.sub(r'(?<=\d)\s(?=\d)', '', '123 abc 1234 456')
'123 abc 1234456'

您不需要正則表達式

if all(part.isdigit() for part in data.split()):
    data = data.replace(" ", "")

您可以使用以下正則表達式:

re.sub('^(\d+) (\d+)$', r'\1\2', s)

這是一個正則表達式,可以執行您想要的操作:

re.sub(r"(?P<digit_before>\d)\s(?P<digit_after>\d)",r"\g<digit_before>\g<digit_after>",s)

暫無
暫無

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

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