Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex match the words from a string without the start and end space

I'm trying to match some words from a string but with no success.

Let's say, for example, i have this string:

"word , word , two words, word"

What i'm trying to do is match the words, but without the space from start or end. But it should accept the spaces from in between the words. The array resulted from the match should be:

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

Could someone help or give me some insight on how would i go about doing this?

Thank you

Edit: what I've tried and succeed is doing it in two parts:

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

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

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

But would like to do it only through regular expression and have no idea how to do it.

like image 905
user3477993 Avatar asked Dec 05 '22 12:12

user3477993


2 Answers

\w[\w ]*?(?:(?=\s*,)|$)

Explanation:

\w[\w ]*?

Matches word characters with 0 or more spaces in between, but never at the start. (lazy)

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

This non-capturing group looks ahead for spaces followed by ,, or the end of string.

Try it here.

like image 78
Sweeper Avatar answered Jan 12 '23 14:01

Sweeper


You can just split on comma surrounded by optional spaces on either side:

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

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

console.log(arr);

//=> ["word", "word", "two words", "word"]
like image 34
anubhava Avatar answered Jan 12 '23 15:01

anubhava