簡體   English   中英

使用python中的regex將字符串中的第一個數字更改為“#”

[英]Change first digit in a string to '#' using regex in python

import re    
sentence = "the cat is called 303worldDomination"    
print re.sub(r'\d', r'#', sentence)

但是,這會用'#'替換字符串中的所有數字

我只希望字符串中的第一個數字被'#'替換

您可以使用count參數指定只應進行一次替換(即第一次匹配):

>>> re.sub(r'\d', r'#', sentence, count=1)
'the cat is called #03worldDomination'

使用錨點和捕獲組。

re.sub(r'^(\D*)\d', r'\1#', sentence)
  • ^聲稱我們剛開始。

  • (\\D*)將捕獲開頭存在的所有非數字字符。 因此,組索引1包含開頭的所有非數字字符。

  • 所以這個正則表達式將匹配第一個數字字符。 在此,捕獲了除第一個數字之外的所有字符。 我們可以通過在替換部分中指定它們的索引號來引用這些捕獲的字符。

  • r'\\1#'將使用組索引1 + #符號中存在的字符替換所有匹配的字符。

例:

>>> sentence = "the cat is called 303worldDomination"
>>> re.sub(r'^(\D*)\d', r'\1#', sentence)
'the cat is called #03worldDomination'

暫無
暫無

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

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