[英]Splitting string with regular expression to make it array without empty element
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?
有谁知道我在我的模式中犯错误或如何解决它?
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 |
你甚至可以使用
[^\\|]+
要匹配任何你要的比赛,但|
There is no mistake. 没有错。 This is absolutely correct behavior (how would
split
know that this is not a CSV file with the last column having an empty value?). 这是绝对正确的行为(如何
split
知道这不是一个CSV文件,最后一列有空值?)。 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
split
function to omit empty results. 但是,我似乎无法找到(在JavaScript中)告诉内置
split
函数省略空结果的可能性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.