0

I'm looking for a Regex that would remove all the white spaces from html code present in .aspx file. Here are some of the conditions that the Regex should satisfy:

  1. Whitespaces between strings enclosed between "" or '' should not be removed.
  2. Whitespaces between html attributes/tags, for example like <a href>text1 text2</a>, should not be removed. Html can also start with <! in case of doctype specification. In short, only Whitespaces that appear after a html tag needs to be removed.
  3. Whitespaces between server tags enclosed between <% %>, should not be removed.

If you would be able to provide one single Regex that satisfies all the above condition, it would be great. Otherwise, separate Regex is also fine.

Thanks in advance.

Derin
  • 1
  • 1
    Most of the page is wrapped with tags, except maybe before/after the main tag (``), or `` tags on pages with master pages. Anyway, what are you trying to do? VS can reformat the page, if that's what your after, but I doubt you can find regular expressions that will do what you're after. – Kobi Jan 19 '11 at 06:50
  • 3
    You'll find it very difficult to use regular expressions for this. See http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454. Also, look at the "Related" questions (below and to the right on this page). – Jim Mischel Jan 19 '11 at 06:54
  • Maybe take a look at here: http://stackoverflow.com/questions/728260/html-minification – Martin Buberl Jan 19 '11 at 20:45
  • Is there really any reason why you want to remove whitespaces in your markup? That'll make reading your markup a real nightmare. – Terry Jul 01 '17 at 12:45

1 Answers1

0

A naïve but simple regex trick to do this is to match the whitespaces between > and <.

That'll keep the tags and their text content untouched.

In javascript (js doesn't support lookbehinds):

  • Pattern: >\s+(?=<)
  • Replace with: >

In a regex engine that supports lookbehinds (f.e. PCRE):

  • Pattern: (?<=>)\s+(?=<)
  • Replace with nothing

A test here

LukStorms
  • 28,916
  • 5
  • 31
  • 45