正则表达式基础篇

概念:

\作为转义字符,转义包括它自己在内的所有元素
^表示行开始的位置
$代表行结束的位置
\A代表任意字符串的开始

\z代表任意字符串的结束
\Z匹配字符串的结束位置,除非以\n结束
(可实际测试时\Z和\z并不有用,可能使用方法并不正确)
\b字符边界 \B否定之
[and]即包含a.n,d的字符类
在括号内[and]表示不包含a,n,d的字符类,作否定使用

\d 匹配0-9
\D 匹配非0-9
\w 匹配英文字母,数字,下划线
\W 同样否定\w
\s 任意空白符
\S 否定\s

?元字符作为一个限定字符出现,限制字符出现一次或零次(<=1)
*元字符则匹配零个或多个字符字符(>=0)
+则匹配一次及以上(>=1)
{m,n}则限定具体次数n代表起始量,m代表最终量,m忽略时默认为无穷
{m,n}?则为非贪婪选项

.可以匹配任意字符

[ad]与(a|d)作用相同
[rst]ight与[r-t]ight同意

圆括号的使用特别需要注意
1.对字符或元字符进行分组,对()内字符使用限定字符
2.匹配直接量
3.交替选择
4.在多个选择中作出选择
5.进行捕获

$1代表第一个括号内补充的内容,故$number

更多特性:向前与向后查找
(?:…)非捕获组
(?!…)否定式向前查找
(?<!…)否定式向后查找
(?=…)肯定式向前查找
(?<=…)肯定式向后查找

eg:State(?=s)匹配字符State,但它必须是复数

补充阅读:
(?imx-imx)
turns on/off imx options for rest of regexp.打开i,m,x的选项
(?imx-imx:re)
turns on/off imx options, localized in group.
匹配相关
\1-9
nth previous captured group
&
whole match
`
pre-match
'
post-match
+
highest group matched
特殊匹配字符
[:alnum:]
alpha-numeric characters
[:alpha:]
alphabetic characters
[:blank:]
whitespace - does not include tabs, carriage returns, etc
[:cntrl:]
control characters
[:digit:]
decimal digits
[:graph:]
graph characters
[:lower:]
lower case characters
[:print:]
printable characters
[:punct:]
punctuation characters
[:space:]
whitespace, including tabs, carriage returns, etc
[:upper:]
upper case characters
[:xdigit:]
hexadecimal digits

选项:
/i
case insensitive
/o
only interpolate #{} blocks once
/m
multiline mode - ‘.’ will match newline
/x
extended mode - whitespace is ignored
/[neus]
encoding: none, EUC, UTF-8, SJIS, respectively

Comments

Copyright © 2013 robinhwang Redesgin by RobinHwang