简体   繁体   English

如何用分号分隔逗号,分号和逗号分隔的短语?

[英]How to split comma, semicolon and comma separated phrases with semicolons around?

How to split comma, semicolon and comma separated phrases with semicolons around where it should treat anything between semicolons with a comma as the delimiter, but also delimit just comma and semicolon all together in funcion? 如何用逗号分隔逗号,分号和逗号分隔的短语,它们应该用逗号作为分隔符来处理分号之间的任何内容,还要用逗号分隔逗号和分号?

String of words: 字串:

var words = "apple;banana;apple, banana;fruit"

Regex function separate by , and ; 正则表达式函数分开,和;

 var result = words.split(/[,;]+/);

Result from that function is: 该功能的结果是:

[ "apple", "banana", "apple", " banana", "fruit" ]

But what I am looking to get is this, to have "banana, apple" and treat it as a separate value 但我希望得到的是“香蕉,苹果”,并将其视为一个单独的价值

[ "apple", "banana, apple", " banana", "fruit" ]

So is it possible to combine 2 cases in that function to output as the second example? 那么有可能将该函数中的两个案例组合起来作为第二个例子输出吗? Or maybe some other elegant way? 或者其他一些优雅的方式?

A combination of match and replace can be used. 可以使用匹配和替换的组合。

With the match we take the two patterns we have 通过比赛,我们采用了两种模式

  1. Values between delimiter (?:\\w+;\\w+,) 分隔符之间的值(?:\\w+;\\w+,)
  2. Value not in between delimiter \\w+;? 值不在分隔符\\w+;?

Now based on matched group we just change the values in desired format using replace 现在基于匹配的组,我们只需使用replace更改所需格式的值

 let words = `apple;banana;apple, banana;fruit` let op = words.match(/(?:\\w+;\\w+,)|\\w+;?/g) .map(e=>e.replace(/(?:(\\w+);(\\w+),)|(\\w+);?/g, (m,g1,g2,g3)=> g1 ? g1+', '+g2 : g3 )) console.log(op) 

Array math is easier than regex. 数组数学比正则表达式更容易。

Objective 目的

apple;banana;apple, banana;fruit > [ "apple", "banana, apple", " banana", "fruit" ] apple;banana;apple, banana;fruit > [ "apple", "banana, apple", " banana", "fruit" ]

Remove spaces, split at ; 删除空格,分开; , split at , . 分裂,

Solution

 const words = 'apple;banana;apple, banana;fruit'; const result = words.split(' ').join('').split(';').join(',').split(','); console.log(result); 

Accorting to question apple-banana second example (after this question update) try 按照问题苹果香蕉的第二个例子(在这个问题更新之后)试试

words.split(';');

 var words = "apple;banana;apple, banana;fruit" var result = words.split(';'); console.log(result); 

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

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