help-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Transposing Regular Expression


From: LanX
Subject: Re: Transposing Regular Expression
Date: Mon, 16 Nov 2009 18:13:11 -0800 (PST)
User-agent: G2/1.0

> That's not exactly what I'm looking for as I really need 2 words/
> characters to be swapped.  For instance, swapping "true" and "false"
> in a region.

OK let's talk perl to understand ... Thats what you want?

perl -e '
$_="EXAMPLE true EXAMPLE false EXAMPLE";
%trans=(true=>"false");
%trans=(%trans,reverse %trans);
$pattern=join "|",keys %trans;
s/($pattern)/$trans{$1}/g;
print "OUTPUT: $_";
'

OUTPUT: EXAMPLE false EXAMPLE true EXAMPLE

(please note: if you don't just want a dual swap but a more
complicated permutation, skip the "reverse" part and provide %trans as
needed like e.g. (1=>2, 2=>3, 3=>1))

You can easily adjust the lisp code I gave you to do that, you need to
change the lambda to do a hash look up and call it within one of the
region-replace functions!

Though for me the corresponding lisp code for hashes seem a little
lengthy...

(I now there are alists, but I leave this solution to others)

So why don't you just pipe a region thru the perl script above?

Typing
C-u M-|
perl -pe '
%trans=(true=>"false");
%trans=(%trans,reverse %trans);
$pattern=join "|",keys %trans;
s/($pattern)/$trans{$1}/g;
'

Can be easily adjusted to do what you want.

And if you type C-x ESC ESC you get the corresponding lisp wrapper for
free
---------
(shell-command-on-region (region-beginning) (region-end) "perl -pe '
%trans=(true=>\"false\");
%trans=(%trans,reverse %trans);
$pattern=join \"|\",keys %trans;
s/($pattern)/$trans{$1}/g;
'
" (quote -) (quote -) nil t)
--------


Couldn't be easier... and the call overhead to perl is really not
observable...

HTH
  LanX


reply via email to

[Prev in Thread] Current Thread [Next in Thread]