开发者

Simple Perl string Problem

开发者 https://www.devze.com 2022-12-22 04:02 出处:网络
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 characte

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.


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.


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.


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


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


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

If you want plus to be remain

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


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

精彩评论

暂无评论...
验证码 换一张
取 消