基于多个分隔符分割字符串[/,#,@,''] [英] Split a string based on multiple delimiters [/, #, @, '']
本文介绍了基于多个分隔符分割字符串[/,#,@,'']的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想基于多个分隔符拆分字符串。
I want to split a string based on multiple delimiters.
如何将包含多个字符串的字符串拆分为分隔符?
How to split a string with multiple strings as separator?
例如:
我有一个字符串:/ create #channel'name''对频道的描述'#field1 #field2
我想要一个数组:
/create
#channel
name
description of the channel
#field1
#field2
另一个例子,我有:/ send @user'The messsage'
我想要:
Another example, i have: "/send @user 'A messsage'"
And I want:
/send
@user
A message
如何解决?有什么帮助吗? : - (
How to solve it? Any help, please? :-(
推荐答案
你可以使用正则表达式
/([\/#]\w+|'[\s\w]+')/g
正则表达式解释: https://regex101.com/r/ lE4rJ7 / 3
-
[\ /#@] \w +
:这将匹配以#
开头的字符串,/
或@
-
|
:OR条件 -
'[\\\\\ t] +'
:匹配用引号括起来的字符串
[\/#@]\w+
: This will match the strings that start with#
,/
or@
|
: OR condition'[\s\w]+'
: Matches the strings that are wrapped in quotes
由于正则表达式也会匹配引号,因此需要将其删除。
As the regex will also match the quotes, they need to be removed.
var regex = /([\/#@]\w+|'[\s\w]+')/g;
function splitString(str) {
return str.match(regex).join().replace(/'/g, '').split(',');
}
var str1 = "/create #channel 'name' 'description of the channel' #field1 #field2 @Tushar";
var str2 = "/send @user 'A messsage'";
var res1 = splitString(str1);
var res2 = splitString(str2);
console.log(res1);
console.log(res2);
document.write(res1);
document.write('<br /><br />' + res2);
这篇关于基于多个分隔符分割字符串[/,#,@,'']的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文