# Why this code doesn't work?

**URL:** <https://www.ruby-forum.com/t/why-this-code-doesnt-work/64068>\
**Category:** Ruby\
**Created:** [June 21, 2006, 8:21pm UTC](https://www.ruby-forum.com/t/why-this-code-doesnt-work/64068 "2006-06-21T20:21:04Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![amoeen](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/8e7dd6/32.png) [@amoeen](https://www.ruby-forum.com/u/amoeen)\
**Post date:** [June 21, 2006, 8:21pm UTC](https://www.ruby-forum.com/t/why-this-code-doesnt-work/64068/1 "2006-06-21T20:21:04Z")

</div>

Hi,

I am trying to replace all html tags and spaces with “\*” in a string.

I tried this code:

"as **sd** **“.sub(/\<[\s\S]_?\>| /,"_”)**

It just replaces the 1st occurance.

This code also doen’t work:

"as **sd** **“.sub(/\<[\s\S]_?\>| /){|s| "_”}**

How can I do that?

Thanks,  
Alan

---

<div class="post-metadata">

**Author:** ![amoeen](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/8e7dd6/32.png) [@amoeen](https://www.ruby-forum.com/u/amoeen)\
**Post date:** [June 21, 2006, 8:27pm UTC](https://www.ruby-forum.com/t/why-this-code-doesnt-work/64068/2 "2006-06-21T20:27:14Z")

</div>

On Jun 21, 2006, at 1:21 PM, Alan M. wrote:

> Hi,
> 
> I am trying to replace all html tags and spaces with “\*” in a string.
> 
> I tried this code:
> 
> "as **sd** **“.sub(/\<[\s\S]_?\>| /,"_”)**
> 
> It just replaces the 1st occurance.

Try:

…gsub…

Hope that helps.

James Edward G. II

---

<div class="post-metadata">

**Author:** ![amoeen](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/8e7dd6/32.png) [@amoeen](https://www.ruby-forum.com/u/amoeen)\
**Post date:** [June 21, 2006, 8:37pm UTC](https://www.ruby-forum.com/t/why-this-code-doesnt-work/64068/3 "2006-06-21T20:37:04Z")

</div>

James Edward G. II wrote:

> > It just replaces the 1st occurance.
> 
> Try:
> 
> …gsub…
> 
> Hope that helps.
> 
> James Edward G. II

It’s also worth pointing out that [\s\S] means a character class  
containing all whitespace and non whitespace characters–in other words:  
everything. This is equivalent:

"as **sd** **“.sub(/\<._?\>| /,"_”)**

which replaces [\s\S] with .

Also, if your tags could have line breaks in them, you can add ‘m’ (for  
multiline) to the end of the regular expression literal and then . will  
match newlines as well:

/regex/m

Oh, and if you replace that last space (after the pipe character) with  
\s, then it will match tabs too (or any whitespace for that matter).

Tom
