我正在尝试实现BigInt减一,并希望优化我的代码。现在我只是迭代数字字符串,例如"1241241291919191904124142398623500000000000000“,为了减去1,所有尾随的0都需要替换为9。
我该如何使用regex来做这件事?
使用正则表达式实现BigInt字符串(SubtractOne)函数的聪明方法是什么?它有几个特殊情况。
这是我到目前为止用来匹配尾随零的内容:
m = re.search('(?<=[1-9])0+$', '91000')发布于 2012-04-23 13:57:59
使用lookahead assertion
import re
s = "1241241291919191904124142398623500000000000000"
r = re.compile("""0 # Match 0
(?= # only if the following can be matched here:
0* # zero or more 0s
$ # until the end of the string.
) # End of lookahead assertion""", re.VERBOSE)现在你可以做
>>> r.sub("9", s)
'1241241291919191904124142398623599999999999999'发布于 2012-04-23 14:05:04
然后,另一种可能是使用返回替换的函数
import re
def ReplZeros(matchobj):
return len(matchobj.group(0)) * "9"
text = '1241241291919191904124142398623500000000000000'
res = re.sub(r'0+$', ReplZeros, text)
print text
print res输出
1241241291919191904124142398623500000000000000 1241241291919191904124142398623599999999999999
https://stackoverflow.com/questions/10275135
复制相似问题