Is there a way to use Replace with Regular Expressions but keep a character
in the original string? A simplified example: If we have "< a >" or "<b >"
or "< br>" within a string and we want to remove the spaces, but keep the
character, is there a way this can be done? A Regular Expression can find
the substring with something like "<\s*[a-z]\s*>" (only finds one character),
but the ReplaceWith argument appears to be static. Is there any way to keep
the character?

Thanks!,
Nick

Re: regular expressions to replace but keep character? by ekkehard

ekkehard
Tue Jul 15 09:55:52 CDT 2008

Nick B schrieb:
> Is there a way to use Replace with Regular Expressions but keep a character
> in the original string? A simplified example: If we have "< a >" or "<b >"
> or "< br>" within a string and we want to remove the spaces, but keep the
> character, is there a way this can be done? A Regular Expression can find
> the substring with something like "<\s*[a-z]\s*>" (only finds one character),
> but the ReplaceWith argument appears to be static. Is there any way to keep
> the character?
[...]
You can use $<n> (<n> = number of () in pattern starting with 1) in the
replacement string:

oRE.Pattern = "(<)(\s*)(\S+)(\s*)(>)"
1 2 3 4 5
sRes = oRE.Replace( "< br >", "$1$3$5" )

Re: regular expressions to replace but keep character? by NickB

NickB
Tue Jul 15 10:09:03 CDT 2008

That's exactly what I couldn't find. Thanks!!

"ekkehard.horner" wrote:

> Nick B schrieb:
> > Is there a way to use Replace with Regular Expressions but keep a character
> > in the original string? A simplified example: If we have "< a >" or "<b >"
> > or "< br>" within a string and we want to remove the spaces, but keep the
> > character, is there a way this can be done? A Regular Expression can find
> > the substring with something like "<\s*[a-z]\s*>" (only finds one character),
> > but the ReplaceWith argument appears to be static. Is there any way to keep
> > the character?
> [...]
> You can use $<n> (<n> = number of () in pattern starting with 1) in the
> replacement string:
>
> oRE.Pattern = "(<)(\s*)(\S+)(\s*)(>)"
> 1 2 3 4 5
> sRes = oRE.Replace( "< br >", "$1$3$5" )
>

Re: regular expressions to replace but keep character? by OldPedant

OldPedant
Tue Jul 15 15:34:14 CDT 2008

"ekkehard.horner" wrote:
>
> oRE.Pattern = "(<)(\s*)(\S+)(\s*)(>)"
> 1 2 3 4 5
> sRes = oRE.Replace( "< br >", "$1$3$5" )
>

You can do it a lot simpler than that.

oRE.Pattern = "<\s*([^\s>]+)\s*>"
sRes = oRE.Replace( "< br >", "<$1>" )

Since you *KNOW* that you are looking for <...> and you *KNOW* you want to
retain <...>, just do *NOT* put any of that stuff in the parentheses. So now
only the non-space, non-> characters will be in parens and there's only one
"group" to be plunked into the output.