您的位置:首页 > 其它

Perl正则表达式初步

2010-01-12 08:59 204 查看
Perl的正则表达式功能十分强大,基本上是常用语言中最强大的,很多语言如Java设计正则式支持的时候都参考Perl正则表达式。本文介绍Perl正则表达式中最基本、最常用的部分。

一、正则表达式运算符

=~ 正则表达式匹配运算符,左边是待匹配字符串,右边是正则表达式,匹配结果设置在$1,$2等变量中,在scaler上下文中,成功匹配返回匹配个数,否则返回false。例如 $var =~ /foo/;

!~ 正则表达式匹配运算符,和=~ 不同的是它忽略匹配结果,且返回值相反。例如 $var !~ /foo/;

正则表达式运算符右边是正则表达式,有如下三种形式:
1. 匹配模式 m/pattern/igmsoxc
m表示match,pattern是正则式内容,分隔符/可以用任意其他字符如#替换,igmsoxc是可选的参数,意义如下:
i 忽略大小写
g 匹配所有符合的(默认是匹配第一个符合的)
m 多行模式,^和$分别匹配行的开始和结尾(默认匹配字符串的开始和结尾)
s 单行模式,“.” 匹配“/n”(默认不匹配)
o compile pattern Once
x eXtended legibility - free whitespace and comments
c don't reset pos on failed matches when using /g

2. 存储模式 qr/pattern/imsox
qr将正则表达式存储到一个变量中,这样可以反复使用,可选项意义与m相同

3. 替换模式 s/pattern/replacement/igmsoxe
s代表substitutes,将匹配的模式pattern替换为replacement,多了一个可选项:
e 将replacement作为一个表达式执行

4. 一次性匹配模式 ?pattern?
和m/pattern/相同,但是只进行一次匹配,?不能用其他分隔符替换

二、基本语法元素

/ 字符转义
. 匹配除/n外的任意字符
^ 匹配行或字符串开头
$ 匹配行或字符串结尾
* 0个或多个
+ 1个或多个
? 0个或1个
{...} 指定个数
[...] 字符类,匹配括号中的任意一字符
(...) 匹配组,匹配后可以用$1,$2等获取相应的匹配组
(?:...) 聚集,匹配后不能$1,$2等获取相应的匹配组,速度会快些
| 前者或后者,一般和括弧配合使用
/1, /2 ... 正则式中反引用匹配组

三、常见转义字符

/a Alarm (beep)
/e Escape
/f Formfeed
/n Newline
/r Carriage return
/t Tab
/037 Any octal ASCII value
/x7f Any hexadecimal ASCII value
/x{263a} A wide hexadecimal value
/cx Control-x
/N{name} A named character

/l Lowercase next character
/u Titlecase next character
/L Lowercase until /E
/U Uppercase until /E
/Q Disable pattern metacharacters until /E
/E End case modification
/b word boudariy

四、字符类

[...]匹配括号中的任意一个字符,但是当第一个字符是^时是相反的,匹配除了括号中的字符外的任意字符。另外还有a-z这样的简写方式代替a到z的所有字符。例如:
[amy] Match 'a', 'm' or 'y'
[f-j] Dash specifies "range"
[f-j-] Dash escaped or at start or end means 'dash'
[^f-j] Caret indicates "match any character _except_ these"

一些字符类有更简单的表达方式,如:
/d A digit [0-9]
/D A nondigit [^0-9]
/w A word character [a-zA-Z0-9_]
/W A non-word character [^a-zA-Z0-9_]
/s A whitespace character [ /t/n/r/f]
/S A non-whitespace character [^ /t/n/r/f]

五、特殊标记

^ Match string start (or line, if /m is used)
$ Match string end (or line, if /m is used) or before newline
/b Match word boundary (between /w and /W)
/B Match except at word boundary (between /w and /w or /W and /W)
/A Match string start (regardless of /m)
/Z Match string end (before optional newline)
/z Match absolute string end
/G Match where previous m//g left off

六、重复

Maximal Minimal Allowed range
------- ------- -------------
{n,m} {n,m}? Must occur at least n times but no more than m times
{n,} {n,}? Must occur at least n times
{n} {n}? Must occur exactly n times
* *? 0 or more times (same as {0,})
+ +? 1 or more times (same as {1,})
? ?? 0 or 1 time (same as {0,1})
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: