正则表达式

来源:互联网 发布:java 日期转换字符串 编辑:程序博客网 时间:2024/04/27 06:16

*    匹配包含前一个字符任意个数的字符串(0个或多个)
      如"1133*"将匹配包含113且在113后有若干个3的字符串。因此它会匹配113,51133,11345等
      如"113*"将匹配包含11且在11后有若干个3的字符串,因些它会匹配11,1145,11345 等
 
.    匹配除了换行符之外的任意一个字符(1个)。
     如"13."匹配包含13且13后有任意一个字符的情况。因些它会匹配134,13135,等。
     但不匹配13。

^    1。匹配行首字符集 2。否定  
     是这两种中的哪种需根据上下文来定。
     如^comp匹配行首为comp的字符串
     如"[^b-d]" 匹配除了从b到d范围内所有的字符. (这里的^就表示了否定)

$    匹配行尾。
     "^$"匹配空行
 
 
[]    匹配[]中的任意一个字符。
     如"[xyz]" 匹配字符x, y, 或z.
     如"[c-n]" 匹配从字符c到n之间的任意一个字符.
     如"[B-Pk-y]" 匹配从B到P 或从k到y的任意一个字符.
     如"[a-z0-9]" 匹配任意小写字母或数字.
     如"[^b-d]" 匹配除了从b到d范围内所有的字符. (这里的^就表示了否定)
 
/    转义字符,将紧跟其后的字符表达为字面意思。

/</>精确匹配一个单词,如/<love/>将精确匹配love这个单词

X/{n/}匹配n个X字符。
     如a/{4/}表匹配aaaa.
     如[0-9]/{5/}表匹配5个数字。

X/{n,/}同上,但X个数最少是n个
     如a/{4,/}表匹配4个或4个以上的a.

X/{n,m/}同上,但X个数介于n与m这间。
     如a/{2,4/}表匹配2个,3个,或4个a.
 
 
  经常使用的正则表达式举例
 
^       行首
$       行尾 
^the    以the开头的行
[Nn][Oo]  NO,No,nO,no
^oneword$  只有oneword一个单词的行
^$        空行
^.*$    任意行
^......$  只有6个字符的行
[^0-9/$]  非数字或$
^/^q    以^q开始的行
[0-9]/{2/}-[0-9]/{2/}-[0-9]/{4/}  日期格式dd-mm-yyyy
[0-9]/{3/}/.[0-9]/{3/}/.[0-9]/{3/}/.[0-9]/{3/} IP地址


还有一种POSIX Character Classes,格式为[:class:]
如:
· [:alnum:] matches alphabetic or numeric characters. This is equivalent to A?Za?z0?9.
· [:alpha:] matches alphabetic characters. This is equivalent to A?Za?z.
· [:blank:] matches a space or a tab.
· [:cntrl:] matches control characters.
· [:digit:] matches (decimal) digits. This is equivalent to 0?9.
· [:graph:] (graphic printable characters). Matches characters in the range of ASCII 33 ? 126. This
             is the same as [:print:], below, but excluding the space character.
·
· [:lower:] matches lowercase alphabetic characters. This is equivalent to a?z.
· [:print:] (printable characters). Matches characters in the range of ASCII 32 -126. This is the
             same as [:graph:], above, but adding the space character.
· [:space:] matches whitespace characters (space and horizontal tab).
· [:upper:] matches uppercase alphabetic characters. This is equivalent to A?Z.
· [:xdigit:] matches hexadecimal digits. This is equivalent to 0?9A?Fa?f.