Gandalf StormCrow
Gandalf StormCrow

Reputation: 26212

Using regex, how to replace white space with no characters?

How to replace from regex many empty/blank characters with none? ex:

<div class="someClass" id="someID"> 
...bunch of elements/content 
<input type="button" name="myInput" id="inputID" title="myInput Title" /> 
...bunch of elements/content 
</div> 

when replaced :

<a class="myselector" rel="I need this value"></a><div class="someClass" id="someID">...bunch of elements/content<input type="button" name="myInput" id="inputID" title="myInput Title" />...bunch of elements/content</div> 

Upvotes: 3

Views: 888

Answers (1)

Max Shawabkeh
Max Shawabkeh

Reputation: 38603

The expression \s+ will match one or more whitespace characters. Replace it with an empty string to remove them. E.g., in Python:

cleaned = re.sub(r'\s+', '', original)

If you plan to do this to HTML, you may damage it. At least replace with a single space instead:

cleaned = re.sub(r'\s+', ' ', original)

Or use a proper HTML manipulation library.

Upvotes: 2

Related Questions