regex to remove all whitespaces except between brackets

后端 未结 6 2110
我在风中等你
我在风中等你 2021-01-06 13:01

I\'ve been wrestling with an issue I was hoping to solve with regex.

Let\'s say I have a string that can contain any alphanumeric with the possibility of a substrin

6条回答
  •  猫巷女王i
    2021-01-06 13:57

    This doesn't sound like something you really want regex for. It's very easy to parse directly by reading through. Pseudo-code:

    inside_brackets = false;
    for ( i = 0; i < length(str); i++) {
        if (str[i] == '[' )
            inside_brackets = true;
        else if str[i] == ']'
            inside_brackets = false;
        if ( ! inside_brackets && is_space(str[i]) )
            delete(str[i]);
    }
    

    Anything involving regex is going to involve a lot of lookbehind stuff, which will be repeated over and over, and it'll be much slower and less comprehensible.

    To make this work for nested brackets, simply change inside_brackets to a counter, starting at zero, incrementing on open brackets, and decrementing on close brackets.

提交回复
热议问题