Regex question; match whitespace OR nothing

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
I asked this on comp.lang.javascript, but haven't had any replies.
Regex really isn't language specific, though, so you guys might know
the answer better, anyway.

I have a section that may, or may not, include a whitespace. Like

var string = "<b><p>Jason</p> </b>";

I'm wanting to do this:

string = string.replace(/<b><p>jason<\/p> <\/b>/gi, "Jason");

But the problem is that the whitespace between </p> and </b> might NOT
exist. I'm doing it like this, but I know that it's wrong because it
would find anything, not just a whitespace:

string = string.replace(/<b><p>jason<\/p>(.*)<\/b>/gi, "Jason");

I'm pretty sure that this isn't right, but it's the direction I was

string = string.replace(/<b><p>jason<\/p>(\s*|(.)*?)<\/b>/gi,

What's the correct way to match a whitespace, or nothing?

Re: Regex question; match whitespace OR nothing

On Fri, 4 Feb 2011 21:22:35 -0800 (PST), jwcarlton put finger to keyboard
and typed:

Quoted text here. Click to load it

A regular expression to match a single whitespace or nothing would be


the \s matches a whitespace, and the ? says to match it zero or one time
only. Putting that into your pattern gives this:


This will match either of these:

  <b><p>Jason</p> </b>

but not this

  <b><p>Jason</p>  </b>

I'm not familiar enough with javascript to say for certain what the correct
code would be, but your syntax looks similar to PHP's preg_match. In which
case, I'm fairly sure that this will work for you:

  string = string.replace(/<b><p>jason<\/p>\s?<\/b>/gi, "Jason");

If you want to match zero or more whitespaces, then replace the ? with a *,
like this:

  string = string.replace(/<b><p>jason<\/p>\s*<\/b>/gi, "Jason");

That will match all three of my examples above, including the one with two

All of the above assumes, of course, that Javascript's regular expression
parsing is PCRE (although I think that the above would work with PERE as
well). As far as I'm aware, that is the case.



Site Timeline