Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Here, I have example javascipt string:

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?

like image 274
scx Avatar asked Nov 07 '12 11:11

scx


People also ask

How do I convert a string to an array in Regex?

To split a string by a regular expression, pass a regex as a parameter to the split() method, e.g. str. split(/[,. \s]/) . The split method takes a string or regular expression and splits the string based on the provided separator, into an array of substrings.

How do you split a string into an array?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

Can we split string using Regex?

split(String regex) method splits this string around matches of the given regular expression. This method works in the same way as invoking the method i.e split(String regex, int limit) with the given expression and a limit argument of zero. Therefore, trailing empty strings are not included in the resulting array.

Can you use split on an array?

The split() method splits (divides) a string into two or more substrings depending on a splitter (or divider). The splitter can be a single character, another string, or a regular expression. After splitting the string into multiple substrings, the split() method puts them in an array and returns it.


1 Answers

I always liked matching everything I always hated split but:

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

Matching instead of splitting:

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

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

DEMO

like image 122
Javier Diaz Avatar answered Sep 28 '22 02:09

Javier Diaz