hankphone
hankphone

Reputation: 123

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!

Upvotes: 7

Views: 21911

Answers (3)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627065

You can replace any one or more whitespace chunks in between two tags using a single regular expression:

(?s)(?:\G(?!\A)|<tags>(?=.*?</tags>))(?:(?!</?tags>).)*?\K\s+

See the regex demo. Details

  • (?s) - a DOTALL inline modifier, makes . match line breaks
  • (?:\G(?!\A)|<tags>(?=.*?</tags>)) - either the end of the previous successful match (\G(?!\A)) or (|) <tags> substring that is immediately followed with any zero or more chars, as few as possible and then </tags> (see (?=.*?</tags>))
  • (?:(?!</?tags>).)*? - any char that does not start a <tags> or </tags> substrings, zero or more occurrences but as few as possible
  • \K - match reset operator
  • \s+ - one or more whitespaces (NOTE: use \s if each whitespace must be replaced).

SublimeText settings: enter image description here

Upvotes: 0

jwpfox
jwpfox

Reputation: 5242

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.

Upvotes: 6

Federico Piazza
Federico Piazza

Reputation: 31035

You have just to use a simple regex like:

\s+

And replace it with with a comma.

Working demo

enter image description here

Upvotes: 12

Related Questions