简体   繁体   English

根据多个分隔符 [/, #, @, ''] 拆分字符串

[英]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?如何用多个字符串作为分隔符分割一个字符串?

For example:例如:

I have a string: "/create #channel 'name' 'description of the channel' #field1 #field2"我有一个字符串: "/create #channel 'name' 'description of the channel' #field1 #field2"

And I want an array with:我想要一个数组:

/create
#channel
name
description of the channel
#field1
#field2

Another example, i have: "/send @user 'A messsage'" And I want:另一个例子,我有: "/send @user 'A messsage'"我想要:

/send
@user
A message

How to solve it?如何解决? Any help, please?请问有什么帮助吗? :-( :-(

here the solution without Regx这里没有 Regx 的解决方案

var multiSplit = function (str, delimeters) {
    var result = [str];
    if (typeof (delimeters) == 'string')
        delimeters = [delimeters];
    while (delimeters.length > 0) {
        for (var i = 0; i < result.length; i++) {
            var tempSplit = result[i].split(delimeters[0]);
            result = result.slice(0, i).concat(tempSplit).concat(result.slice(i + 1));
        }
        delimeters.shift();
    }
    return result;
}

simply use简单地使用

multiSplit("/create #channel 'name' 'description of the channel' #field1 #field2",['/','#','@',"'"])

output输出

Array [ "", "create ", "channel ", "name", " ", "description of the channel", " ", "field1 ", "field2" ]

You can use regex您可以使用正则表达式

/([\/#]\w+|'[\s\w]+')/g

For regex explanation: https://regex101.com/r/lE4rJ7/3正则表达式说明: https : //regex101.com/r/lE4rJ7/3

  1. [\\/#@]\\w+ : This will match the strings that start with # , / or @ [\\/#@]\\w+ :这将匹配以#/@开头的字符串
  2. | : OR condition : 或条件
  3. '[\\s\\w]+' : Matches the strings that are wrapped in quotes '[\\s\\w]+' : 匹配用引号括起来的字符串

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);

this one works for your case, but not with split:这个适用于您的情况,但不适用于拆分:

('[^']+'|[^\\s']+)

note: you will still have to trim the single-quotes!注意:您仍然需要修剪单引号!

here is an example: http://jsfiddle.net/k8s8r77e/1/这是一个例子: http : //jsfiddle.net/k8s8r77e/1/

but i can't tell you if it will always work.但我不能告诉你它是否总是有效。 Parsing in that way is not really what regex is for.以这种方式解析并不是正则表达式的真正用途。

Something like this might work.. but would have to be tweaked to not wipe out apostrophes像这样的东西可能会起作用..但必须进行调整才能不消除撇号

var w = "/create #channel 'name' 'description of the channel' #field1 #field2";

var ar = w.split();

ar.forEach(function(e, i){  
    e = e.replace(/'/g, '')
    console.log(e)
})

fiddle: http://jsfiddle.net/d9m9o6ao/小提琴: http : //jsfiddle.net/d9m9o6ao/

There is something inconsistent in the example you gave, you either split by those fields or give them as fields markers, but you seem to mix.您提供的示例中有一些不一致的地方,您要么按这些字段拆分,要么将它们作为字段标记提供,但您似乎混合了。 Take you first example, in the original string you have 'name', but in the result you strip it of the ' and have only name, while #channel keeps the #.以你的第一个例子为例,在原始字符串中你有 'name',但在结果中你把它去掉了 ' 并且只有名字,而 #channel 保留了 #。 Anyways you have 2 options:无论如何,您有2个选择:

String.split takes a regular expression so you can use: String.split 采用正则表达式,因此您可以使用:

var re = /['\/@#"]+\s*['\/@#"]*/;

var str = "/create #channel 'name' 'description of the channel' #field1 #field2";
var parts = str.split(re);

You get an array of your tokens.你会得到一系列你的令牌。 Note the first one in this case is empty, just remove empty strings before using the parts array.请注意,在这种情况下,第一个是空的,只需在使用部分数组之前删除空字符串。

Or, use string.match with a regexp:或者,将 string.match 与正则表达式一起使用:

var re = /['\/@#"][^'\/@#"]*/g;
var parts = str.match(re);

ES6 version avoiding regex (regular language can be complex as it was originally designed for AI, pre-unix) ES6 版本避免使用正则表达式(常规语言可能很复杂,因为它最初是为 AI 设计的,在 unix 之前)

 const source = "this is a; string with; multiple delimiters; and no regex"; function multiSplit(str, delimiters) { return delimiters.reduce((acc, cur) => { if (typeof(acc) === 'string') { return acc.split(cur); } return acc.map(a => a.split(cur)).flat(1); }, str); } const split = multiSplit(source, [';', ' ']); console.log(split);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM