Search code examples
htmlregextagssublimetext2sublimetext3

Sublime Text regex to find and replace whitespace between two xml or html tags?


I'm using Sublime Text and I need to come up with a regex that will find the whitespaces between a certain opening and closing tag and replace them with commas.

Example: Replace white space in

<tags>This is an example</tags>

so it becomes

<tags>This,is,an,example</tags>

Thanks!


Solution

  • This will find instances of

    <tags>...</tags> 
    

    with whitespace between the tags

    (<tags>\S+)\W(.+</tags>)
    

    This will replace the first whitespace with a comma

    \1,\2
    

    Open Find and Replace [OS X Cmd+Opt+F :: Windows Ctrl+H]

    Use the two values above to find and replace and use the 'Replace All' option. Repeat until all the whitespaces are converted to commas.

    The best answer is probably a quick script but this will get you there fairly fast without needing to do any coding.