簡體   English   中英

使用 python 中的 re.sub() 替換句子中的數字

[英]Replace a digit in a sentence using re.sub() in python

我正在嘗試使用re.sub()來替換句子中的總分。 例如,在Your score for quiz01 is 6/8. , 我想把總分換成9 ,預期的 output 是Your score for quiz01 is 6/9. .

我嘗試了下面的代碼,但它一直返回(??([a-zA-Z]+))(:.?+.)([0-9]\/9). ** (??([a-zA-Z]+))(:.?+.)([0-9]\/9). ** 我應該如何修改正則表達式以正確替換數字?

import re
s = '** Your score for quiz01 is 6/8. **'

print(re.sub(r'(?!([a-zA-Z]+))(?:.+?)([0-9]\/[0-9])', r'(?!([a-zA-Z]+))(?:.+?)([0-9]\/9)', s))

# result print as (?!([a-zA-Z]+))(?:.+?)([0-9]\/9). **

您可以使用

re.sub(r'(\d/)\d(?!\d)', r'\g<1>9', s)

請參閱正則表達式演示 正則表達式匹配

  • (\d/) - 第 1 組(使用替換模式中的\g<1>明確反向引用;需要\g<N>語法,因為在反向引用之后,有一個數字):一個數字和一個/字符
  • \d - 一個數字
  • (?!\d) - 后面沒有任何其他數字。

請參閱Python 演示

import re
s = "Your score for quiz01 is 6/8."
print( re.sub(r"(\d/)\d(?!\d)", r"\g<1>9", s) )
# => Your score for quiz01 is 6/9.

暫無
暫無

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

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