Perl Learning - 15 (s///)
发布时间:2020-12-15 21:02:16 所属栏目:大数据 来源:网络整理
导读:s/// is the most common expression using RE to do "search and replace". ? s/patten/replace/ searches the 'patten' and replaces it to 'replace'. ? 'patten' is the patten we talked in perlRE,it can be a variable though. 'replace' is the char
s/// is the most common expression using RE to do "search and replace".
?
s/patten/replace/ searches the 'patten' and replaces it to 'replace'.
?
'patten' is the patten we talked in perlRE,it can be a variable though.
'replace' is the characters whichever you want to replace the result of search,it can be variable too.
?
$_="He's out bowling with Barney tonight.";
s/Barney/Fred/;?# Barney replaced by Fred s/with (w+)/agaist $1's team/; print "$_n";
?
s/// returns a value: replace success returns true,failure returns false.
?
$_="fred flintstone";
if(s/fred/wilma/){ ?print "Successfully replaced fred with wilma!n"; ?print "$_n"; }
?
/g flag can replace all the result,instead of once by default.
?
$_="home,sweet home!";
s/home/cave/g; print "$_n";
?
$_="?? Input???? data?may have????? extra whitespace.? ";
s/s+/ /g; print "$_n";
?
Above example is used to compress multiple whitespaces to one single space.
?
We can use other symbol in other then s///
?
$_="?? Input???? data?may have????? extra whitespace.? ";
s<s+>[ ]g; s(^s+)<>g; s#s+$##g; print "$_n";
?
Note if use the patten symbols different from replace symbols,they need two pairs of () [] {} ... those pair'ed symbols. /// ### !!! ... those single don't have to.
?
Flags /i /x /s used in m// can also be used in s///
?
$_="hello 1
hello 2 wilma again LOL Fred,WILMA come on! _ _END_ _ line 1 line 2 line 3"; ?s#wilma#Wilma#gi; ?s{_ _END_ _.*}{}gs; ?print;
?
All wilma/wiLMA/WIlmA are replaced by Wilma,lines starting with '_ _END_ _' all?are deleted.
?
Also,=~ can be used to replace variables other than $_ by default.
?
$file_name =~ s#^.*/##s;?# remove all unix style path
?
/U changes all characters after it to upper case;
/L changes all characters after it to lower case; /E close the window of /U or /L; /u changes one character after it to upper case; /l changes one character after it to loser case; /u/L changes one character after it to upper case and all other characters to lower case; /l/U changes one character after it to lower case and all other characters to upper case.
?
$_ =“I saw Barney with Fred.”;
s/(fred|barney)/U$1/gi;
?
$_="I saw barney with FREd.";
s/(w+) with (w+)/uL$2E with uL$1/i; print "$_n";
?
They can be used in " " as well:
?
$name="fred flintstone";print "Hello,Lu$nameE,would you LIKE to play a game?n";
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |