- 需求:从124fddr323532${xxxasdsafxx}253${bnm}23354${abcd}233545xx54${666}233545xxxxx这类字符串中获取${}中的内容。注意${xxx}的个数是不确定的。
使用了match和exec两种方式实现,直接上代码(更推荐第二种):
function getMatchedStrs (str) {
var reg = /${(.+?)}/
var reg_g = /${(.+?)}/g
var result = str.match(reg_g)
var list = []
for (var i = 0; i < result.length; i++) {
var item = result[i]
list.push(item.match(reg)[1])
}
return list
}
function getExecStrs (str) {
var reg = /${(.+?)}/g
var list = []
var result = null
do {
result = reg.exec(str)
result && list.push(result[1])
} while (result)
return list
}
- Python中:
def findAllStrs():
strs = '124fddr3235323423532${xxxasdsafxx}253${bnm}23354${abcd}233545xx54${666}233545xxxxx'
pattern = '${(.+?)}'
reg = re.compile(pattern)
result = reg.findall(strs)
# print result
return result