Home All Groups Group Topic Archive Search About

Use regex.replace to replace a group #, not the whole match string

Author
2 Jun 2006 9:53 PM
justin.mayes
hello all -

An example. You have a regular expression to locate certain html tags.

"(<)[^a-z]"


This will find every instance of a "<" character that is not followed
by a letter. The match will include the 2nd character ("<>") wheras
group 1 will just include the "<" character.

when you do a regex.replace it automatically replaces the matches but I
want to just replace group1.

so      regex.replace ("<>", "(<)[^a-z]", "x")      would match "<>"
and retuen "x" when what i really want is to replace just the < and end
up with "x>" Does that make sense?

thanks for any help provided.

Author
2 Jun 2006 10:07 PM
JR
I got it :-)

I can use the negative look ahead assertion. This makes it so it only
matches the "<" i want.

"<(?![a-z/])"


justin.ma***@gmail.com wrote:
Show quoteHide quote
> hello all -
>
> An example. You have a regular expression to locate certain html tags.
>
> "(<)[^a-z]"
>
>
> This will find every instance of a "<" character that is not followed
> by a letter. The match will include the 2nd character ("<>") wheras
> group 1 will just include the "<" character.
>
> when you do a regex.replace it automatically replaces the matches but I
> want to just replace group1.
>
> so      regex.replace ("<>", "(<)[^a-z]", "x")      would match "<>"
> and retuen "x" when what i really want is to replace just the < and end
> up with "x>" Does that make sense?
>
> thanks for any help provided.