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

≯℡__Kan透↙ 提交于 2021-02-04 15:15:46

问题


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!


回答1:


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.




回答2:


You have just to use a simple regex like:

\s+

And replace it with with a comma.

Working demo

enter image description here




回答3:


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:



来源:https://stackoverflow.com/questions/25923015/sublime-text-regex-to-find-and-replace-whitespace-between-two-xml-or-html-tags

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!