简体   繁体   English

JavaScript 正则表达式不会在逗号或制表符空间上拆分

[英]JavaScript regex won't split on comma or tab space

I am trying to split text from a file that could be a csv or tab delimited.我正在尝试从可能是 csv 或制表符分隔的文件中拆分文本。 Using split function with "," works for csv files, but when try and pass in a regex like this "/[\s,;\t\n]+/" bunches all the text together as one continuous string.使用带有","的拆分 function 适用于 csv 文件,但是当尝试传入像这样的正则表达式时, "/[\s,;\t\n]+/"将所有文本捆绑在一起作为一个连续的字符串。

Is there a regex that will split the string whether the text is separated either by a comma or a tab?是否有一个正则表达式可以拆分字符串,无论文本是用逗号还是制表符分隔? The files will only be either csv or tab delimited.这些文件只能是 csv 或制表符分隔。

The regex /[,\t]/gm will find any comma or tab in a string.正则表达式/[,\t]/gm将在字符串中找到任何逗号或制表符。 You can use it inside the split method in order to split the string.您可以在 split 方法中使用它来拆分字符串。 Your regex also find spaces for the \s and ;您的正则表达式还会为\s;找到空格and line feed for \n (which you don't wrote you want split on).和换行符\n (你没有写你想要拆分)。 Down here you can see an example of how I used this regex.在这里,您可以看到我如何使用此正则表达式的示例。

 const stringToSplit =`RegExr was created by gskinner.com, and is proudly hosted by Media Temple. Edit the Expression & Text to see matches. Roll over matches or the expression for details. PCRE & JavaScript flavors of RegEx are supported. Validate your expression with Tests mode. The side bar includes a Cheatsheet, full Reference, and Help. You can also Save & Share with the Community, and view patterns you create or favorite in My Patterns. Explore results with the Tools below. Replace & List output custom results. Details lists capture groups. Explain describes your expression in plain English.` const re = /[,\t]/gm; const splitted = stringToSplit.split(re); console.log(splitted)

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

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