javascript 用正则表达式拆分字符串以使其成为没有空元素的数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13268770/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 18:16:20  来源:igfitidea点击:

Splitting string with regular expression to make it array without empty element

javascriptregex

提问by scx

Here, I have example javascipt string:

在这里,我有示例 javascipt 字符串:

example_string = "Answer 1| Answer 2| Answer 3|";

I am trying to get array like this using regular expression:

我正在尝试使用正则表达式获取这样的数组:

Array ["Answer 1", " Answer 2", " Answer 3"]

I have tried:

我努力了:

result = example_string.split('/[|]+/g');

and also with the following patterns

以及以下模式

'/[|]+/g'
'/[|]+\b/g'
'/[|]+[^$]/g'

And I am still getting an array with empty element at the end of it:

我仍然得到一个包含空元素的数组:

 Array ["Answer 1", " Answer 2", " Answer 3", ""]

That cause me lot of trouble. Does anyone know where I am making mistake in my pattern or how to fix it?

那给我带来很多麻烦。有谁知道我在我的模式中犯了什么错误或如何解决它?

回答by Javier Diaz

I always liked matching everything I always hated split but:

我总是喜欢匹配我一直讨厌分裂的所有东西,但是:

Regex for splitting: (\|(?!$))DEMO

用于拆分的正则表达式:(\|(?!$))DEMO

Matching instead of splitting:

匹配而不是拆分:

Regex: (?:([\w\s]+)\|?)

正则表达式: (?:([\w\s]+)\|?)

You can even use [^\|]+To match whatever you have to match BUT |

您甚至可以使用[^\|]+To 匹配您必须匹配的任何内容 BUT|

DEMO

演示

回答by Martin Ender

There is no mistake. This is absolutely correct behavior (how would splitknow that this is not a CSV file with the last column having an empty value?). If you know your string always ends in |, you could remove the last one first manually. Or you could just take away the last element of the array if it is empty. However, I can't seem to find a possibility (in JavaScript) to tell the built-in splitfunction to omit empty results.

没有错误。这是绝对正确的行为(如何split知道这不是最后一列具有空值的 CSV 文件?)。如果您知道您的字符串总是以 结尾|,您可以先手动删除最后一个。或者,如果数组为空,您可以删除数组的最后一个元素。但是,我似乎找不到(在 JavaScript 中)告诉内置split函数省略空结果的可能性。