我有以下字符串:
{!target.useremail!}-{!target.name}
结果我想拥有以下数组:
["useremail", "-", "name"]
我也可以使用以下字符串:
{!target.useremail!}-{!target.name} {!target.help!}{!target.thanks!}
这将导致:
["useremail", "-", "name", " ", "help", "thanks"]
使用RegExp可以实现这个目的吗?是的,什么是RegExp以及它是如何工作的?
使用以下RegExp,我可以检索第一项:{!target。(。*)!}
一些评论:
答案 0 :(得分:2)
{!(.*?)!}(?:(.+?)|){!(.*?)!}
您可以使用此功能。只需抓住groups
或captures
。请参阅演示。
答案 1 :(得分:2)
您可以使用:
var re = /{!target\.(\w+)!?}(?=$|([^{]+)|{)/g;
var str = '{!target.useremail!}-{!target.name} {!target.help!}{!target.thanks!}';
var m;
var arr=[];
while ((m = re.exec(str)) !== null) {
if (m.index === re.lastIndex)
re.lastIndex++;
arr.push(m[1]);
if (m[2])
arr.push(m[2]);
}
console.log(arr);
["useremail", "-", "name", " ", "help", "thanks"]
答案 2 :(得分:1)
{!target\.([^!]+)!}|([^{]+)|{/g
会在搜索组中为您的搜索的每个部分提供值:
[
{
"match": 1,
"children": [
{
"group": 1,
"start": 9,
"end": 18,
"value": "useremail"
}
]
},
{
"match": 2,
"children": [
{
"group": 2,
"start": 20,
"end": 21,
"value": "-"
}
]
},
{
"match": 3,
"children": [
{
"group": 1,
"start": 30,
"end": 34,
"value": "name"
}
]
},
{
"match": 4,
"children": [
{
"group": 2,
"start": 36,
"end": 37,
"value": " "
}
]
},
{
"match": 5,
"children": [
{
"group": 1,
"start": 46,
"end": 50,
"value": "help"
}
]
},
{
"match": 6,
"children": [
{
"group": 1,
"start": 61,
"end": 67,
"value": "thanks"
}
]
}
]
答案 3 :(得分:0)
如果您的输入始终采用此样式:
{!target.somevalue!} SOMECAHRS {!target.somevalue!}
你应该做的是:
var string = '{!target.somevalue!} ffdf {!target.somevalue!}';
var regex = /\{!target\.(\w+)!\}/g;
var re = regex.exec(string);
现在re将是一个数组,somevalue值将从re [1]索引开始,直到re.index length