Regex matches words from a string without start and end space

I am trying to match some words from a string, but without success.

Say, for example, I have this line:

"word , word , two words, word"

What I'm trying to do is consistent with the words, but without a space from beginning to end. But he must take the spaces between words. The array obtained as a result of the match should be:

["word","word","two words","word"]

Can someone help or give me some idea on how I can do this?

thank

Edit: what I have tried and succeed does in two parts:

match(/[^(,)]+/g)

and using a map to remove all spaces from the resulting array:

map(value => value.trim());

But I would like to do this only through regular expression and I do not know how to do it.

+4
source share
4 answers
\w[\w ]*?(?:(?=\s*,)|$)

Explanation:

\w[\w ]*?

0 , . ()

(?:(?=\s*,)|$)

, , , ,, .

.

+5

, :

var str = "word , , word , two words, word";

var arr = str.split(/(?:\s*,\s*)+/);

console.log(arr);

//=> ["word", "word", "two words", "word"]
Hide result
+4

:

(\w+\s*\w+)

  • 1 ,
  • 0 N ( : , , , , ),
  • 1 .

http://www.rexegg.com/regex-quickstart.html

+3

, , \1

\s*([\w\s]+)\s*
+3

Source: https://habr.com/ru/post/1690312/


All Articles