tags:

views:

166

answers:

7

Something like this:

/[abcd]/[efgh]/

The idea is that a will get replaced with e, b with f, c with g and so on.

Ideally, this should be language independent. If that isn't possible, I have an alternate solution (because this regex is generated by some code, I can make one for each of the possible replacements).

+7  A: 

In perl, tr performs character replacement:

tr/abcd/efgh/

Will do what your example suggests.

Anon.
You mean "a cold day" becomes "e golh hey"?
Martinho Fernandes
Yes. That is what `tr` does. You can even use range shorthands - forex `tr/a-z/A-Z/` will convert characters to uppercase.
Anon.
That's really cool. Btw `tr` stands for translate.
Martinho Fernandes
tr does exactly this. rare one-to-one mapping between question and feature. +1
George
+2  A: 

In sed, the y/// expression does just that.

It's also a synonym for tr/// in perl

mmsmatt
A: 

In Python its possible with passing Lambda function to re.sub

>>> import re
>>> d={"a":"e","b":"f","c":"g","d":"h"}
>>> re.sub("[abcd]",lambda x:d[x.group(0)],"abcd")
'efgh'

Normally, just mapping "a" to "e", is not really useful.

It will be more useful like following case, when you want to change a,b,c,d to e,f,g,h when "x" is before those. It can be done with one regex.

>>> re.sub("(?<=x)[abcd]",lambda x:d[x.group(0)],"xaxbxcxdaabbccdd")
>>>'xexfxgxhaabbccdd'
S.Mark
Yeah, it works, but why use regexes then?
Martinho Fernandes
Added one more case, It could be more useful than [abcd] to [efgh] example.
S.Mark
A: 

well, with Python, shouldn't have to use regex as well

>>> import string
>>> FROM="abcd"
>>> TO="efgh"
>>> table=string.maketrans(FROM,TO)
>>> print "a cold day".translate(table)
e golh hey
A: 

If you really want to do it in a regex: some languages can have an expression as the right hand side of a regexp, so maybe something like (Perl):

$foo =~ s/x([a-d])/"x".chr(ord($1)+4)/e

would do the trick, although it is kind of awful, and it probably not really what you need.

Sharkey
A: 

In php this can be done by passing arrays in the preg_replace.

$outputText = preg_replace($arraySource, $arrayTarget, $inputText);

$arraySource[0] is replaced by $arrayTarget[0]

$arraySource[1] is replaced by $arrayTarget[1]

$arraySource[2] is replaced by $arrayTarget[2]

  .                              .

  .                              .

  .                              .

  .                              .

and so on.

RahulJ
Or using `strtr($str, 'abcd', 'efgh')` (in this specific case).
jensgram
A: 

There's a UNIX command 'tr' which does this, as an addition to the Perl and Python answers...

Steven Schlansker