regex - backwards?

J

John

Hi

$x =~s |a|b|;

That will replace the first 'a' by 'b' in $x.

Is there any obvious tweek so that it replaces the last occurrence of 'a'?

Regards
John
 
J

Jürgen Exner

John said:
$x =~s |a|b|;

That will replace the first 'a' by 'b' in $x.

Is there any obvious tweek so that it replaces the last occurrence of 'a'?

The most simple solutions are often the best solutions:
reverse;
s///;
reverse;
As long as you don't do that hundreds of thousands of times or you are
dealing with gigantic strings there shouldn't be much of a problem with
this trivial approach.

jue
 
D

Danny Woods

John said:
Hi

$x =~s |a|b|;

That will replace the first 'a' by 'b' in $x.

Is there any obvious tweek so that it replaces the last occurrence of 'a'?

Yes: regex lookahead:

$x =~ s|a(?=[^a]*$)|b|;

Can be read as "an 'a', followed by zero or more non-'a's up until the
end of line"

Cheers,
Danny.
 
J

Jim Gibson

John <[email protected]> said:
Hi

$x =~s |a|b|;

That will replace the first 'a' by 'b' in $x.

Is there any obvious tweek so that it replaces the last occurrence of 'a'?

$x =~ s/(.*)a/$1b/;

should do it, taking advantage of the fact that the * modifier is
greedy.
 
S

sln

Hi

$x =~s |a|b|;

That will replace the first 'a' by 'b' in $x.

Is there any obvious tweek so that it replaces the last occurrence of 'a'?

Regards
John

If you don't want to use lookahead as Danny suggested,
which is probably easiest, a couple of alternatives:

$aaa =~ s/a ([^a]*) $ /b$1/x;
# or
substr ($aaa, pos($aaa)-1, 1) = 'b' if ($aaa =~ / .*a /xg);

Of these, lookahead may be quickest. Have to benchmark them.

-sln
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

RegEx 0
Regex replace problem 2
Issue with textbox script? 0
Clickable link conversion regex? 0
Search a Large files backwards 7
regex question 7
Replacement Problem 1
Can D simulated by H terminate normally? 4

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,576
Members
45,054
Latest member
LucyCarper

Latest Threads

Top