Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1752301
  • 博文数量: 335
  • 博客积分: 4690
  • 博客等级: 上校
  • 技术积分: 4341
  • 用 户 组: 普通用户
  • 注册时间: 2010-05-08 21:38
个人简介

无聊之人--除了技术,还是技术,你懂得

文章分类

全部博文(335)

文章存档

2016年(29)

2015年(18)

2014年(7)

2013年(86)

2012年(90)

2011年(105)

分类: Python/Ruby

2011-08-16 19:19:38

Chapter 7. Regular Expressions

Regular expressions are a powerful and standardized way of searching, replacing, and parsing text with complex patterns of characters. If you've used regular expressions in other languages (like Perl), the syntax will be very familiar, and you get by just reading the summary of the re module to get an overview of the available functions and their arguments.

正则表达式是一种进行字符搜索,替换,以及使用复杂的字符串模式来解析文本的,非常强大和标准的方式。如果你在其它的语言中有使用正则表达式的经验(比如Perl),语法是非常类似的,你就可以直接跳过前面部分,去阅读re moudle小结,来获得一个该模块中所有函数以及它们的参数的整体轮廓。

7.1. Diving In

Strings have methods for searching (indexfind, and count), replacing (replace), and parsing (split), but they are limited to the simplest of cases. The search methods look for a single, hard-coded substring, and they are always case-sensitive. To do case-insensitive searches of a string s, you must call s.lower() or s.upper() and make sure your search strings are the appropriate case to match. The replace andsplit methods have the same limitations.

字符串有搜索的方法(index,find,count,替换方法(replace,以及解析(split,但是它们受限于最简单的情况。搜索方法查找一个单一的,硬编码的字符字串,而且这通常是大小写敏感的。为了对字符s产进行大小写不敏感的查找,你必须调用s.lower()或是s.upper(),并确定你搜索的字符串使用了合适的情况来进行匹配。Replacesplit方法有同样的限制。

If what you're trying to do can be accomplished with string functions, you should use them. They're fast and simple and easy to read, and there's a lot to be said for fast, simple, readable code. But if you find yourself using a lot of different string functions with if statements to handle special cases, or if you're combining them with split and join and list comprehensions in weird unreadable ways, you may need to move up to regular expressions.

如果你正在打算做的事可以使用字符串函数来完成,那你就应该使用它们。这些函数效率很高,而且非常简单,易于理解。对于这些高效可读的代码,还有许多可以说。但是你如果发现你自己正在使用字符串函数并使用if语句来处理不同的情况,或是你正在以一种奇怪的晦涩的方式来使用splitjoin以及列表综合操作来进行字符串综合操作,那你或许应该尝试一下正则表达式。

Although the regular expression syntax is tight and unlike normal code, the result can end up being more readable than a hand-rolled solution that uses a long chain of string functions. There are even ways of embedding comments within regular expressions to make them practically self-documenting.

尽管正则表达式的语法很是难懂而且与普通代码不同,结果比你使用长长的字符串函数的手卷的解决方法更加具有可读性。甚至存在几种方式可以在正则表达式内嵌入注释来让正则表达式本身更加的文档化。

 

阅读(1099) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~