js使用正則表達式獲取字符串中特定的字符

  1. 需求:從124fddr323532${xxxasdsafxx}253${bnm}23354${abcd}233545xx54${666}233545xxxxx這類字符串中獲取${}中的內容。注意${xxx}的個數是不肯定的。

使用了match和exec兩種方式實現,直接上代碼(更推薦第二種):python

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
    }
  1. 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
相關文章
相關標籤/搜索