Split string by all spaces except those in parentheses

对着背影说爱祢 提交于 2021-02-19 03:59:20

问题


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.


回答1:


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)



回答2:


Not a single regexp but does the job. Removes the parentheses and splits the text by spaces.

var words = line.replace(/[\(\)]/g,'').split(" ");



回答3:


One approach which is useful in some cases is to replace spaces inside parens with a placeholder, then split, then unreplace:

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

var result = line.replace(/\((.*?)\)/g, m => m.replace(' ', 'SPACE'))
  .split(' ')
  .map(x => x.replace(/SPACE/g, ' '));
  
console.log(result);
                 


来源:https://stackoverflow.com/questions/41075573/split-string-by-all-spaces-except-those-in-parentheses

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!