regular expressions

S

sonet

my $keyword=shift;
$keyword=~s/(&.*?)$//;
print $keyword;

i want to replace the last word like &xyz.

ex:
if $keyword='123123;&12;212222&123' then output 123123;&12;212222

if $keyword='123123;&12;212222&123;' then output 123123;&12;212222&123;

but i alaways got the error result (123123;)
 
B

Brian Wakem

sonet said:
my $keyword=shift;
$keyword=~s/(&.*?)$//;
print $keyword;

i want to replace the last word like &xyz.

ex:
if $keyword='123123;&12;212222&123' then output 123123;&12;212222

if $keyword='123123;&12;212222&123;' then output 123123;&12;212222&123;

but i alaways got the error result (123123;)


The problem is not described too well. All of the below work, take your
pick according to what it is you are actually trying to do.

$keyword=~s/&\d+$//;
$keyword=~s/&[^;]+$//;
$keyword=~s/&.{3}$//;
 
C

cju.kuo

like this...try it!

my $keyword='123123;&12;212222&123;';
$keyword=~s/\&123([;])*$/$1/;
print $keyword;
 
D

Dr.Ruud

sonet schreef:
my $keyword=shift;
$keyword=~s/(&.*?)$//;
print $keyword;

i want to replace the last word like &xyz.

ex:
if $keyword='123123;&12;212222&123' then output 123123;&12;212222

if $keyword='123123;&12;212222&123;' then output
123123;&12;212222&123;

but i alaways got the error result (123123;)

The '?' for minimal matching, doesn't work "from the right".


To remove everything starting at the last '&' up to the end, where the
characters between that last '&' and the end can not be ';'

s/&[^&;]*$//


Since you call it a word, you could also use \w (see perlre)

s/&\w*$//
 
M

Michele Dondi

like this...try it!

my $keyword='123123;&12;212222&123;';
$keyword=~s/\&123([;])*$/$1/;

& is not a special metacharachter, it doesn't need to be quoted.
C<[;]> is the same as C<;>.
The $ is redundant (in this case, i.e. with no modifiers), since * is
greedy anyway.


Michele
 

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

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top