![](/img/trans.png)
[英]Replace one word of a string if that word is within a specific number of words of another word
[英]Replace Word Number string with Word_Number
我在Python中使用Regex將Word Number
對替換為以下形式Word_Number
。
例如:
import re
text = 'Opera 20 Opera 19 Version Hello World'.lower()
text = re.sub(r'(\[a-z]+)( )(\d)', r'\1_\2', text)
# text = re.sub(r'\([a-z]+)(.*)(\d+)', r'\1_\2', text)
print(text)
預期產量:
opera_20 opera_19 version hello world
有人可以幫我嗎?
我想這就是你所追求的
text = re.sub(r'([a-z]+)( )(\d+)', r'\1_\3', text)
的變化是
[
必填 \\d
需要重復 \\3
而不是\\2
您也可以刪除捕獲組中的空白區域
re.sub(r'([a-z]+)\s+(\d+)', r'\1_\2', text)
試試這個正則表達式
\b([a-zA-Z]+)\b\s(\d+)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.