1

I know this might be very easy to some,,

I have a simple string like this @¨0­+639172523299 (with characters before a mobile number). My question is, how do i remove all the characters before the plus(+)? What i know is to remove a known character as follows:

$number =~ tr/://d; (if i want to remove a colon)

But here, I want all characters before '+' to be removed.

1
  • 2
    usual general comment about how it's 'Perl' and not 'PERL'. if you're learning from sources using the term 'PERL', then there's a chance that they are out-of-date or not advocating good, current programming practices.
    – plusplus
    Mar 5, 2010 at 9:03

6 Answers 6

4

To remove everything up to and including the first +, you can do:

$number ~= s/.*\+//;

If you want to keep the +, you can put that into the replacement:

$number ~= s/.*\+/+/;

The above says: Match "anything" (the .*) followed by a + (+ is a special character in regular expressions, which is why it needs the backslash escape) and replace it with nothing (or in the above example, replace it with a single +).

Note that the above will strip out everything up to the LAST + in the string, which may not be what you want. If you want to keep strip out everything up to the FIRST + in a string, you can do:

$number =~ s/[^+]*\+//;

or

$number =~ s/[^+]*\+/+/; # Keep the +

The difference from the first regular expression being the [^+]* instead of .*, which means "match any character except a +".

For more information on Perl's regular expressions, the perldoc perlre manual page is pretty good, as is O'Reilly's Mastering Regular Expressions book.

0
2

in the simplest case

$string =~ s/^.*\+//;

if you have more than one "+" before the mobile number

$string="@+0+0­+639172523299";
@s=split /\+/,$string;
print $s[-1];

In fact, you can just use split() instead of regex. Its easier.

1
my $string = '@¨0­+639172523299';
$string =~ s/(.*)(?=\+)//;
print $string;
0
$number =~ s/^.*\+//;
0

s/(.*?\+)(.*)/\2/;

If you want plus to be remain

s/(.*?)(\+)(.*)/\2\3/;

0
my $str="@¨0­+639172523299";
if($str=~/(\D+)(\+[0-9]+)/)
{
  print $2;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.