![](/img/trans.png)
[英]Python regex match string of 8 characters that contain both alphabets and numbers
[英]Python: String formatting a regex string that uses both '%' and '{' as characters
我有以下正則表達式,它允許我使用re.split解析“20%+”,“20%”或“20% - 50%”等百分比。
'([0-9]{1,3}[%])([+-]?)'
我想使用字符串格式來傳遞序列標識符(即'+ - ')作為config.py中的參數。
SERIES = '+-'
我試過的兩種方法產生了錯誤。 新式格式化會遇到以下錯誤(由於{m,n}用法):
>>> import config
>>> regex = '([0-9]{1,3}[%])([{0}]?)'.format(config.SERIES)
KeyError: '1,3'
舊式格式有自己的問題(由於'%'字符):
>>> import config
>>> regex = '([0-9]{1,3}[%])([%s]?)' % (config.SERIES)
unsupported format character ']' (0x5d) at index 14
我無法在正則表達式中運行轉義字符。 有關如何做到這一點的任何想法?
謝謝,
麥克風
您可以使用%%
使用舊式格式插入百分號:
'([0-9]{1,3}[%%])([%s]?)' % (config.SERIES)
類似地,對於新式格式,將大括號加倍:
'([0-9]{{1,3}}[%])([{0}]?)'.format(config.SERIES)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.