Search code examples
regexsublimetext3

How to remove spaces between words using regular expression in sublime text?


I have some values look like these:

$lang['Delivery Charge'] = 'Delivery Charge';

$lang['Frequently Asked Questions'] = 'Frequently Asked Questions';

I am using this regular expression to select the variable index:

\$lang\['.*'\]

Now how can I replace the spaces between words for only the variable indexes not in values.

I mean my final result will look like:

$lang['DeliveryCharge'] = 'Delivery Charge';

$lang['FrequentlyAskedQuestions'] = 'Frequently Asked Questions';

Thanks in advance!


Solution

  • You could use

    (?:\$\w+\['|\G(?!^))\w+\K\h+
    

    Explanation

    • (?: Non capture group
      • \$\w+\[' Match $ and 1+ word chars and ['
      • | Or
      • \G(?!^) Assert the position at the end of the previous match, not at the start
    • ) Close non capture group
    • \w+ Match 1+ word chars
    • \K\h+ Reset the match buffer and match 1+ horizontal whitespace chars

    And replace with an empty string

    Regex demo

    To also check for a closing ] , where there can not be square brackets in between, you could add a positive lookahead:

    (?:\$\w+\['|\G(?!^))\w+\K\h+(?=[^][]*'])
    

    Regex demo