Is this possible with regular expressions?
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 alte开发者_运维知识库rnate solution (because this regex is generated by some code, I can make one for each of the possible replacements).
In perl, tr
performs character replacement:
tr/abcd/efgh/
Will do what your example suggests.
In sed, the y///
expression does just that.
It's also a synonym for tr///
in perl
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
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.
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'
There's a UNIX command 'tr' which does this, as an addition to the Perl and Python answers...
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.
精彩评论