regex to remove all whitespaces except between brackets

后端 未结 6 2099
我在风中等你
我在风中等你 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条回答
  •  Happy的楠姐
    2021-01-06 13:54

    This works for me:

    (\[.+?\])|\s
    

    Then you simply pass in a replacement value of $1 when you call the replace function. The idea is to look for the patterns inside the brackets first and make sure they're untouched. And then every space outside the brackets gets replaced with nothing.

    Note that I tested this with Regex Hero (a .NET regex tester), and not in PHP. So I'm not 100% sure this will work for you.

    That was an interesting one. Sounded simple at first, then seemed rather difficult. And then the solution I finally arrived at was indeed simple. I was surprised the solution didn't require a lookaround of any sort. And it should be faster than any method that uses a lookaround.

提交回复
热议问题