Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string by all spaces except those in parentheses

I'm trying to split text the following like on spaces:

var line = "Text (what is)|what's a story|fable called|named|about {Search}|{Title}"

but I want it to ignore the spaces within parentheses. This should produce an array with:

var words = ["Text", "(what is)|what's", "a", "story|fable" "called|named|about", "{Search}|{Title}"];

I know this should involve some sort of regex with line.match(). Bonus points if the regex removes the parentheses. I know that word.replace() would get rid of them in a subsequent step.

like image 914
Optimus Avatar asked Feb 05 '23 13:02

Optimus


1 Answers

Use the following approach with specific regex pattern(based on negative lookahead assertion):

var line = "Text (what is)|what's a story|fable called|named|about {Search}|{Title}",
    words = line.split(/(?!\(.*)\s(?![^(]*?\))/g);
  
console.log(words);
  • (?!\(.*) ensures that a separator \s is not preceded by brace ((including attendant characters)
  • (?![^(]*?\)) ensures that a separator \s is not followed by brace )(including attendant characters)
like image 121
RomanPerekhrest Avatar answered Feb 08 '23 05:02

RomanPerekhrest