1、 JS
let content = '烟花易冷人事易分 而你在问我是否还认真 千年后累世情深还有谁在等 ――《${name}》${time}'
var reg = /\$\{(\w+)\}/g
let variableArrey = content.match(reg)
console.log(variableArrey)
VM456:7 (2) ["${name}", "${time}"]
- 结果
["${name}", "${time}"]
- 规则里的内容,重点:
.replace(reg,'$1')
let content = '烟花易冷人事易分 而你在问我是否还认真 千年后累世情深还有谁在等 ――《${name}》${time}'
var reg = /\$\{(\w+)\}/g
let variableArrey = content.match(reg).map(item => item.replace(reg,'$1'))
console.log(variableArrey)
- 结果
["name", "time"]
2、Golang
func TestReg(t *testing.T) {
str := "${a}${b}"
vars, err := getVar(str)
if err != nil {
t.Error(t)
return
}
t.Log(convert.MustJsonString(vars))
}
func getVar(str string) (list []string, err error) {
reg := regexp.MustCompile(`\${([^\${}]?)}`)
if reg == nil {
err = fmt.Errorf("正则表达式错误:%s", str)
return
}
list = reg.FindAllString(str, -1)
// list = > ["${a}","${b}"]
for i, v := range list {
list[i] = reg.ReplaceAllString(v, "$1")
}
return
}
- 结果
=== RUN TestReg
--- PASS: TestReg (0.00s)
math_test.go:131: ["a","b"]
PASS
Process finished with exit code 0
有疑问加站长微信联系(非本文作者)