简体   繁体   English

用逗号分隔的字符串的此正则表达式有什么问题?

[英]What is wrong with this regex for comma-separated string?

I'm trying to convert a comma or semicolon separated string into an array, but handling before conversion several omission from users (double commas, space after comma or semicolon). 我正在尝试将逗号或分号分隔的字符串转换为数组,但是在转换前要处理用户的一些遗漏(双逗号,逗号或分号后的空格)。 In the example: 在示例中:

myStr = "item1, item2,,, this is item3; item4 , "

I want to get: 我想得到:

myArray = ["item1", "item2", "this is item3", "item4"]

My actual regex is: 我的实际正则表达式是:

myArray = myStr.split(/[(,\s);,]+/);

But, although I'm adding parenthesis to the combination comma-space (,\\s) the regex are catching the spaces inside the third item. 但是,尽管我将括号添加到组合逗号空间(,\\s)但正则表达式却捕获了第三项内部的空格。 Any advice what could be wrong with regex? 任何建议正则表达式可能有什么问题吗?

Try this (edited) : 试试这个(编辑)

 var myStr = "item1, item2,,, this is item3; item4 , "; var myArray = myStr.split(/\\s*[,;]+\\s*/).filter(Boolean); alert(myArray); 

[] only contains single characters or character classes and only matches one character at a time. []仅包含单个字符或字符类,并且一次仅匹配一个字符。 Therefore, [(,\\s);,] really means any of these characters are matched: (),; 因此, [(,\\s);,]实际上意味着这些字符中的任何一个都匹配:( (),; or whitespace. 或空白。

There are easier approaches than regex. 有比regex更简单的方法。 Try this: 尝试这个:

myArray = myStr
  .split(/[;,]/)                 
  .map(function (str) { 
    return str.replace(/(^\s+)|(\s+$)/g, ''); // Trim whitespace
  }) 
  .filter(Boolean);              // Filter away the empty strings

I think you need to ensure you always match at least one non-white-space character. 我认为您需要确保始终匹配至少一个非空格字符。 Try this: 尝试这个:

myArray = myStr.split(/[\s]*[,;][,;\s]*/);
var myArray = myStr.split(/(?: , | ; | ,| ;|, |; |;|,)+/);  

 Then do a quick trim() and verify if the item has content other than whitespace

Would effectively split a string using , or ; 将使用或有效分割字符串。 as the separator 作为分隔符

 var myStr = "item1, item2,,, this is item3; item4 , "; var myArray = myStr.split(/(?: , | ; | ,| ;|, |; |;|,)+/); var newArray = []; for (var i=0; i<myArray.length; i++) { var checkArray = myArray[i].trim(); if (checkArray.length > 0) { newArray.push(myArray[i]); } } myArray = newArray; console.log(myArray); 


ANSWER 2 答案2

The best answer I could come up with was one I made by combining @Jacob's answer and my answer above. 我能想到的最好的答案是我结合@Jacob的答案和上面的答案而得出的答案。

This will effectively Accomplish the job in the fastest way possible 这将以最快的方式有效完成工作

 var myStr = "item1, item2,,, this is item3; item4 , "; var myArray = myStr.split(/(?:,|;)+/).map(function (str) { return str.replace(/(^\\s+)|(\\s+$)/g, ''); }).filter(Boolean); console.log(myArray); 

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

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