Page 1 of 1

replace two characters within a markup tag

Posted: Wed Jun 17, 2009 3:04 am
by norest
Believe me, I've been trying!

Attempting a a search & replace using regular expressions so that:

<color>FFFF00FF</color>

becomes:

<color>7FFF00FF</color>

The first 2 characters must become "7F" - but the remaining 6 characters should remain the same.

The colour will vary - so the regular expression should FIND anything within the color tag!

My FIND attempt - /<color>.{8}<\/color>/ - certainly doesn't work!

Preferences set to POSIX.

Posted: Wed Jun 17, 2009 4:31 am
by norest
The good thing about posting to forums is that you often figure out the answer in framing the question

This worked for me --

Code: Select all

FIND:
<color>([[:xdigit:]]{2})([[:xdigit:]]{6})</color>

REPLACE:
<color>7F\2</color>
I thought the replacement variables were from 0-9 ... I expected the second replacement variable to be \1 ... but \2 seems to work??

Posted: Wed Jun 17, 2009 4:54 am
by ak47wong
norest wrote:I thought the replacement variables were from 0-9 ... I expected the second replacement variable to be \1 ... but \2 seems to work??
The replacement variables (backreferences) start from \1, so \2 was correct in your example. (The expression \0 is equivalent to &, that is the whole regexp matched.) You could have left out the grouping around the first two digits since you're not making any backreference to them, in which case you would have:

Code: Select all

FIND:
<color>[[:xdigit:]]{2}([[:xdigit:]]{6})</color>

REPLACE:
<color>7F\1</color>
Andrew

Posted: Wed Jun 17, 2009 5:40 am
by norest
@ak47wong - thanks