Chinaunix首页 | 论坛 | 博客
  • 博客访问: 851383
  • 博文数量: 253
  • 博客积分: 6891
  • 博客等级: 准将
  • 技术积分: 2502
  • 用 户 组: 普通用户
  • 注册时间: 2010-11-03 11:01
文章分类

全部博文(253)

文章存档

2016年(4)

2013年(3)

2012年(32)

2011年(184)

2010年(30)

分类: Python/Ruby

2011-10-12 16:32:12

 s/// will make just one replacement, even if others are possible.  The  /g modifier tells
s/// to make all possible nonoverlapping* replacements:
  1. $_ = "home, sweet home!";
  2. s/home/cave/g;
  3. print "$_\n"; # "cave, sweet cave!"
Once we show collapsing whitespace, everyone wants to know about stripping leading
and trailing whitespace. That’s easy enough, in two steps:
s/^\s+//;  # Replace leading whitespace with nothing
s/\s+$//;  # Replace trailing whitespace with nothing
We could do that in one step with an alternation and the /g flag, but that turns out to
be a bit slower, at least when we wrote this. The regular expression engine is always
being tuned, but to learn more about that, you can get Jeffrey Friedl’s Mastering Regular
Expressions (O’Reilly) and find out what makes regular expressions fast (or slow).
s/^\s+|\s+$//g;  # Strip leading, trailing whitespace.

The \U escape forces what follows to all uppercase:
$_ = "I saw Barney with Fred.";
s/(fred|barney)/\U$1/gi;  # $_ is now "I saw BARNEY with FRED."
Similarly, the \L escape forces lowercase. Continuing from the previous code:
s/(fred|barney)/\L$1/gi;  # $_ is now "I saw barney with fred."

By default, these affect the rest of the (replacement) string, or you can turn off case
shifting with \E:
s/(\w+) with (\w+)/\U$2\E with $1/i;  # $_ is now "I saw FRED with barney."

When written in lowercase (\l and \u ), they affect only the next character:
s/(fred|barney)/\u$1/ig;  # $_ is now "I saw FRED with Barney."
You can even stack them up. Using \u with \L means “all lowercase, but capitalize the
first letter”:*
s/(fred|barney)/\u\L$1/ig;  # $_ is now "I saw Fred with Barney."
As it happens, although we’re covering case shifting in relation to substitutions, these
escape sequences are available in any double-quotish string:
print "Hello, \L\u$name\E, would you like to play a game?\n";


阅读(442) | 评论(0) | 转发(0) |
0

上一篇:RE precedence

下一篇:split join

给主人留下些什么吧!~~