regex to remove all whitespaces except between brackets

后端 未结 6 2069
我在风中等你
我在风中等你 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条回答
  •  太阳男子
    2021-01-06 13:53

    How to do this depends on what should be done with:

    a b [ c [ d [ e ] f ] g
    

    That is ambiguous; possible answers are at least:

    • ab[ c [ d [ e ] f ]g
    • ab[ c [ d [ e ]f]g
    • error out; the brackets don't match!

    For the first two cases, you can use regexps. For the third case, you'd be much better off with a (small) parser.

    For either case one or two, split the string on the first [. Strip spaces from everything before [ (that's obviously outside of the brackets). Next, look for .*\] (case 1) or .*?\] (case 2) and move that over to your output. Repeat until you're out of input.

提交回复
热议问题