[英]Remove spaces in group of numbers just after a string
我正在嘗試刪除緊跟在字符串后面的數字之間的空格(在本例po box
為po box
)。
我可以使用re.match
和一些替換邏輯來實現這一點,但是如果我可以使用條件re.sub
來做到這一點肯定會更好。
如何將捕獲組集成到正則表達式子中?
我在下面嘗試了許多不同版本的代碼,但無濟於事:
my_string = "po box 12 34 5 heisenburg 902 rr 15"
re.sub(r'(?:po box)([0-9 ]+)', r'', my_string)
預期成績:
po box 12 59 76 => po box 125976
po box 56 56 barry 56 87 => po box 5656 barry 56 87
barry box 56 87 => barry box 56 87
我把它放在一起,達到了預期的效果,但並不理想。
my_string = "po box 12 34 5 heisenburg 902 rr 15"
match = re.match(r'po box([0-9 ]+)', my_string)
if match:
# remove spaces between numbers
spaceless_numbers = match.group(1).replace(' ', '')
# get original string positions
start = match.span(1)[0]
end = match.span(1)[1]
# get start and end portions of the original string
first_part = my_string[:start]
second_part = my_string[end:]
# concatenate start + spaces removed section + end
print('{} {} {}'.format(first_part, spaceless_numbers, second_part).strip())
您可以使用
import re
my_strings = ["po box 12 34 5 heisenburg 902 rr 15", "po box 12 59 76","po box 56 56 barry 56 87","barry box 56 87"]
p = re.compile(r'\b(po\s+box\s*)(\d+(?:\s+\d+)+)')
for s in my_strings:
print(s, ' => ', p.sub(lambda x: f"{x.group(1)}{''.join(c for c in x.group(2).split())}", s))
請參閱Python 演示。 輸出:
po box 12 34 5 heisenburg 902 rr 15 => po box 12345 heisenburg 902 rr 15
po box 12 59 76 => po box 125976
po box 56 56 barry 56 87 => po box 5656 barry 56 87
barry box 56 87 => barry box 56 87
正則表達式是
\b(po\s+box\s*)(\d+(?:\s+\d+)+)
請參閱正則表達式演示。 細節:
\\b
- 單詞邊界(po\\s+box\\s*)
- 第 1 組: po
, 1+ 個空格, box
, 0+ 個空格(\\d+(?:\\s+\\d+)+)
- 第 2 組:1+ 位數字以及一次或多次出現的 1+ 空格和 1+ 位數字 f"{x.group(1)}{''.join(c for c in x.group(2).split())}"
替換是 Group 1 和 Group 2 的串聯,其中刪除了所有空格。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.