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

J

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.
 
J

JR

I got it :)

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

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top