我有一个这种格式的字符串:
#someID@tn@company@somethingNew@classing@somethingElse@With
可能会有无限的@ -separated单词,但绝对是整个字符串以#
开头我写了下面的正则表达式,虽然它匹配它,但是我不能得到每个@ -separated单词,我得到的是最后一个递归和第一个(以及整个字符串)。如何分别获取元素中每个单词的数组?
(?:^\#\w*)(?:(\@\w*)+) //I know I have ruled out second capturing group with ?: , though doesn't make much difference.
这是我的Javascript代码:
var reg = /(?:^\#\w*)(?:(\@\w*)+)/g;
var x = null;
while(x = reg.exec("#someID@tn@company@somethingNew@classing@somethingElse@With"))
{
console.log(x);
}
这是结果(Firebug,控制台):
["#someID@tn@company@somet...sing@somethingElse@With", "@With"]
0
"#someID@tn@company@somet...sing@somethingElse@With"
1
"@With"
index
0
input
"#someID@tn@company@somet...sing@somethingElse@With"
编辑: 如果可能的话,我希望使用正则表达式输出这样的输出:
["#someID", "@tn", @company", "@somethingNew", "@classing", "@somethingElse", "@With"]
请注意,我想要一个RegExp解决方案。我知道String.split()和String操作。
答案 0 :(得分:1)
您可以使用:
var s = '#someID@tn@company@somethingNew@classing@somethingElse@With'
if (s.substr(0, 1) == "#")
tok = s.substr(1).split('@');
//=> ["someID", "tn", "company", "somethingNew", "classing", "somethingElse", "With"]
答案 1 :(得分:0)
你也可以试试这个正则表达式,
((?:@|#)\w+)
<强>解释强>
()
捕获群组。捕获组内的任何内容都将被捕获。(?:)
它只匹配字符串,但不会捕获任何内容。@|#
文字@
或#
符号。\w+
后跟一个或多个单词字符。或强>
> "#someID@tn@company@somethingNew@classing@somethingElse@With".split(/\b(?=@|#)/g);
[ '#someID',
'@tn',
'@company',
'@somethingNew',
'@classing',
'@somethingElse',
'@With' ]
答案 2 :(得分:0)
没有regExp会更容易:
var str = "#someID@tn@company@somethingNew@classing@somethingElse@With";
var strSplit = str.split("@");
for(var i = 1; i < strSplit.length; i++) {
strSplit[i] = "@" + strSplit[i];
}
console.log(strSplit);
// ["#someID", "@tn", "@company", "@somethingNew", "@classing", "@somethingElse", "@With"]