I want to replace the string “A B C D E F” with “A1 B2 C3 D4 E5” in a single regular expression. Is it possible to have a counter in regular expressions?
Depends what flavor of regex you’re using. In Perl you can say:
my $s = "A B C D E F";
my $n = 0;
$s =~ s/(\w)/$1 .++$n/eg;
…because Perl allows you to execute arbitrary code in the replacement string with the /e flag. But there isn’t a way to do it with “standard” regex primitives that I can think of.
You can’t do it with plain vanilla regular expressions, so you’ll need something like what friedo posted.
Ok. Thanks. It’s Javascript. I tried:
var i = 0;
“A B C D E F”.replace(/ /g, ++i + " "));
- but i doesn’t get incremented before after all the replacements have been made. I now made a version:
var res = “”;
var tmp = “A B C D E F”.split(/ /g);
for (var i = 0; i < tmp.length; i++) res += tmp* + i + " ";
- not so nice.
Does anyone know why this reg exp in perl doenst work;
If there are two carriage returns in my string, this doens’t work.
$message =~ s/
/<p>/g;
But if i use just one
in the replace it does work…
$message =~ s/
/<p>/g;
any idea how i can serach for double
's in string.?
Your question is unrelated to the first in the thread.
Nevertheless: your string probably has DOS-style CRLF line ends. Try
instead of
.