我想在字符串中打印出具有以下模式+2个字符的所有子字符串: 例如,获取子串
$iwantthis*12
$and this*11
来自字符串;
$iwantthis*1231 $and this*1121
在我使用的部分
print re.search('(.*)$(.*) *',string)
我得到$iwantthis*1231
但是如何限制最后一个模式符号后面的字符数*?
问候
答案 0 :(得分:2)
In [13]: s = '$iwantthis*1231 $and this*1121'
In [14]: re.findall(r'[$].*?[*].{2}', s)
Out[14]: ['$iwantthis*12', '$and this*11']
在这里,
[$]
匹配$
; .*?[*]
匹配最短的字符序列,后跟*
; .{2}
匹配任意两个字符。答案 1 :(得分:2)
import re
data = "$iwantthis*1231 $and this*1121"
print re.findall(r'(\$.*?\d{2})', data)
<强>输出强>
['$iwantthis*12', '$and this*11']