![](/img/trans.png)
[英]Regex python - Match newline only if it is followed by number or special character and space
[英]Python regex : adding space after comma only if not followed by a number
僅在以下字符不是數字(9-0)的情況下,我才想在字符串中的逗號前后添加空格。 我嘗試了以下代碼:
newLine = re.sub(r'([,]+[^0-9])', r' \1 ', newLine)
但是似乎\\1
正在使用2個匹配的字符,而不僅僅是逗號。 例:
>>> newLine = "abc,abc"
>>> newLine = re.sub(r'([,]+[^0-9])', r' \1 ', newLine)
"abc ,a bc"
預期產量:
"abc , abc"
我怎樣才能告訴sub
只取“逗號”?
使用這個:
newLine = re.sub(r'[,]+(?![0-9])', r' , ', newLine)
在這里使用負前瞻(?![0-9])
來檢查逗號后面是否沒有數字。
您的正則表達式無法正常工作,因為您將逗號和下一個字符(使用([,]+[^0-9])
分組在一起,並在兩側都留了空格。
更新:如果不僅是逗號和其他內容,還可以將它們放在字符類[]
並使用()
將它們捕獲到\\1
組中
newLine = re.sub(r'([,/\\]+)(?![0-9])', r' \1 ', newLine)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.