C# Regular Expressions Cheat Sheet

来源:互联网 发布:网络金融销售算传销吗 编辑:程序博客网 时间:2024/04/29 15:50

C# Regular Expressions Cheat Sheet

 

Cheat sheet for C# regular expressions metacharacters, operators, quantifiers etc

 

Character
Description\

Marks the next character as either a special character or escapes a literal. For example, "n" matches the character "n". "\n" matches a newline character. The sequence "\\" matches "\" and "\(" matches "(".

Note: double quotes may be escaped by doubling them: "<a href=""...>"

^ Depending on whether the MultiLine option is set, matches the position before the first character in a line, or the first character in the string.$ Depending on whether the MultiLine option is set, matches the position after the last character in a line, or the last character in the string.* Matches the preceding character zero or more times. For example, "zo*" matches either "z" or "zoo".+ Matches the preceding character one or more times. For example, "zo+" matches "zoo" but not "z".? Matches the preceding character zero or one time. For example, "a?ve?" matches the "ve" in "never"..Matches any single character except a newline character.(pattern) Matches pattern and remembers the match. The matched substring can be retrieved from the resultingMatches collection, using Item[0]...[n]. To match parentheses characters ( ), use "\(" or "\)".(?<name>pattern) Matches pattern and gives the match a name.(?:pattern) A non-capturing group(?=...) A positive lookahead(?!...) A negative lookahead(?<=...) A positive lookbehind .(?<!...) A negative lookbehind .x|yMatches either x or y. For example, "z|wood" matches "z" or "wood". "(z|w)oo" matches "zoo" or "wood".{n}n is a non-negative integer. Matches exactly n times. For example, "o{2}" does not match the "o" in "Bob," but matches the first two o's in "foooood".{n,} n is a non-negative integer. Matches at least n times. For example, "o{2,}" does not match the "o" in "Bob" and matches all the o's in "foooood." "o{1,}" is equivalent to "o+". "o{0,}" is equivalent to "o*".{n,m}m and n are non-negative integers. Matches at leastn and at mostm times. For example, "o{1,3}" matches the first three o's in "fooooood." "o{0,1}" is equivalent to "o?".[xyz]A character set. Matches any one of the enclosed characters. For example, "[abc]" matches the "a" in "plain".[^xyz]A negative character set. Matches any character not enclosed. For example, "[^abc]" matches the "p" in "plain".[a-z]A range of characters. Matches any character in the specified range. For example, "[a-z]" matches any lowercase alphabetic character in the range "a" through "z".[^m-z]A negative range characters. Matches any character not in the specified range. For example, "[m-z]" matches any character not in the range "m" through "z".\b Matches a word boundary, that is, the position between a word and a space. For example, "er\b" matches the "er" in "never" but not the "er" in "verb".\B Matches a non-word boundary. "ea*r\B" matches the "ear" in "never early".\d Matches a digit character. Equivalent to [0-9].\D Matches a non-digit character. Equivalent to [^0-9].\f Matches a form-feed character.\k A back-reference to a named group.\n Matches a newline character.\r Matches a carriage return character.\s Matches any white space including space, tab, form-feed, etc. Equivalent to "[ \f\n\r\t\v]".\S Matches any nonwhite space character. Equivalent to "[^ \f\n\r\t\v]".\t Matches a tab character.\v Matches a vertical tab character.\w Matches any word character including underscore. Equivalent to "[A-Za-z0-9_]".\W Matches any non-word character. Equivalent to "[^A-Za-z0-9_]".\num Matches num, where num is a positive integer. A reference back to remembered matches. For example, "(.)\1" matches two consecutive identical characters.\nMatches n, where n is an octal escape value. Octal escape values must be 1, 2, or 3 digits long. For example, "\11" and "\011" both match a tab character. "\0011" is the equivalent of "\001" & "1". Octal escape values must not exceed 256. If they do, only the first two digits comprise the expression. Allows ASCII codes to be used in regular expressions.\xnMatches n, where n is a hexadecimal escape value. Hexadecimal escape values must be exactly two digits long. For example, "\x41" matches "A". "\x041" is equivalent to "\x04" & "1". Allows ASCII codes to be used in regular expressions.\unMatches a Unicode character expressed in hexadecimal notation with exactly four numeric digits. "\u0200" matches a space character.\AMatches the position before the first character in a string. Not affected by the MultiLine setting\ZMatches the position after the last character of a string. Not affected by the MultiLine setting.\GSpecifies that the matches must be consecutive, without any intervening non-matching characters.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

Currently rated 4.51 by 263 people

Date Posted: Saturday, May 19, 2007 8:36 PM
Last Updated: Sunday, June 13, 2010 10:33 AM
Posted by: Mikesdotnetting
Total Views to date: 611779

Comments

Monday, December 29, 2008 10:02 AM from Steve

Thanks. Been quite a while since I last used Regular Expressions. Your cheat sheet is just what the doctor ordered.

 

Tuesday, February 17, 2009 4:33 PM from Dhwanit

Thanks! This was very helpful!

 

Saturday, April 4, 2009 12:11 PM from pat

Maybe also good to mention that "?" can be used to indicate non-greedy match ie .*? Often quite handy

 

Thursday, April 16, 2009 4:32 PM from DJ

Anyone know the correct way to check for the dash/minus "-" character?

 

Thursday, April 16, 2009 8:39 PM from Mike

DJ:

Escape it with a backslash: \-

 

Monday, June 1, 2009 7:12 PM from Jeff

The descriptions for \W and \w are not completely correct.

You say they're equivalent to [A-Za-z0-9] or [^A-Za-z0-9] when in fact \w allows extended ASCII chars to pass through, e.g. accented letters from non-English languages.

 

Friday, July 17, 2009 6:39 PM from Rick

Thanks for the great resource. I was wondering if I could link to your article from a help file I'm creating for my company's product which uses c# regular expressions to search through a text file.

 

Friday, July 17, 2009 7:20 PM from Mike

@Rick

Yes, by all means

 

Thursday, August 13, 2009 12:49 AM from Roland

Cool, but now how do I use it in code?

 

Thursday, August 13, 2009 4:42 PM from Alister

One that's missing:

\k : a back-reference to a named group.

 

Thursday, August 13, 2009 11:02 PM from Mike

@Roland

Huh?

 

Sunday, September 20, 2009 4:35 AM from Tim

I tried using (pattern) to parse out "(Preferred)" from a string and Visual C# 2008 required me to enter it as (\\(Preferred\\)) . So in order to match parentheses characters ( ), it should be listed as "\\(" or "\\)" not "\(" or "\)" as stated above.

 

Tuesday, November 24, 2009 11:32 AM from Tomas

How can I write expression with negative number?.. like Column = -8. It doesn't work and result is empty ..

 

Friday, December 4, 2009 3:03 AM from Steve Wellens

Very nice.

I hope you don't mind me pointing out a very useful, and more importantly free, tool for developing Regular Expressions.

http://www.ultrapico.com/Expresso.htm

 

Friday, December 4, 2009 6:37 AM from Mike

@Steve,

Thanks for that. I've kept meaning to update this entry with a link to Expresso. You've done it for me now :o)

 

Sunday, June 6, 2010 6:51 AM from Marc D

Dude... awesome cheat sheet. I just started learning/using/attempting to use reg expressions, so this list rocks:D One thing I think would be great would be how to put together patterns. Some of the patterns out there are just confusing looking. Anyway.. Good job!

 

Thursday, June 10, 2010 9:38 PM from greensweater

One that's missing: \k : a back-reference to a named group.

as in:

^(?[0-9]*)=\k$

123=123 match
123=456 fail

 

Sunday, June 13, 2010 10:34 AM from Mike

@Alister and greensweater

I've added \k now. Thanks for pointing it out.

 

Monday, June 21, 2010 10:49 AM from Jonas

Regular expression comment(#) is missing.

 

Thursday, July 29, 2010 1:41 PM from chhanda

Excellent

 

Tuesday, August 3, 2010 12:32 PM from vijay

Thanks for your help.

 

Friday, August 20, 2010 5:59 PM from alexitosrv

Nice resource. Also Expresso is such a great tool.

Thank you very much.

 

Monday, September 6, 2010 9:43 PM from Alistair

\x for stripping non printable ascii characters is a life saver for me. The samples on Regexlib.com just don't work in .NET. Thanks for providing this resource. No wonder it's the most popular page on your great site!

 

Thursday, October 7, 2010 4:34 PM from mark

whats the modifier to make searches/matches case insensitive?

thanks

 

Saturday, October 9, 2010 7:46 AM from Mike

@mark

For .NET, you apply it as a RegexOptions parameter: http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regexoptions.aspx

 

Friday, December 3, 2010 7:20 AM from suddu

As Tim said,for parenthesis you should use \\( and \\)

 

Monday, December 13, 2010 4:03 PM from Niels Heurlin

Ok as a cheat sheet. I was hoping for some examples.

 

Wednesday, January 26, 2011 7:42 PM from Dominic

Thanks, this saved my day!

I needed an expression to match anything (including newlines and embedded HTML tags) in the element of an HTML document.

This worked in C#:
pattern = @"";

 

Thursday, May 12, 2011 6:58 PM from dev

please send me regularexpression for
(mm/dd/yyyy HH:MM:SS AM/PM)

Thank you

 

Thursday, May 12, 2011 7:46 PM from Mike

@dev,

You don't need a regular expression. You need DateTime.TryParse().

 

Saturday, August 17, 2013 12:53 AM from Art

Haha, I can't believe you bothered responding to "dev"...

Anyway, thanks for the great resource!

 

Tuesday, December 17, 2013 5:54 PM from Ric

The \un example should be "\u0020", rather than "\u0200"--that would give you Ȁ instead.

=========================================================================================

Regular Expressions

(See also http://linuxreviews.org/beginner/tao_of_regular_expressions andhttp://en.wikipedia.org/wiki/Regular_expressions)

  • To fully utilize shell scripting and certain commands and utilities commonly used in scripts (expr, sed, awk, etc.), you need to know how to use regular expressions.
  • Do not confuse regular expressions with shell globbing (filename expansion).
    • sh/ksh/bash do not normally use regular expressions,but can do file globbing, which use conventions that are similar to regular expressions.
  • Regular expressions are sets of characters and/or metacharacters that represent text patterns.
  • The main uses for regular expressions are text searches and string manipulation.
    • A regular expression matches a single character or a set of characters (a substring or an entire string).

Regexp (regular expression) meta-characters

  • The asterisk * matches any number of repeats of the character string or regexp preceding it,including zero.
     "1133*" matches 11 + one or more 3's + possibly other characters:     113, 1133, 111312, and so forth.                                 
  • The dot . matches any one character, excepta newline.
     "13." matches 13 plus at least one of any character (including a     space): 1133, 11333, but not 13 (additional character missing).
     ".*" matches any number of any characters.
  • The caret ^ matches the beginningofa line,but sometimes, depending on context, negates the meaningofa set of characters in an regexp.
  • The dollar sign $ at the end of an regexp matches the end of a line.
     "^$" matches blank lines.                                       
  • Brackets […] enclose a set of characters to match in a single regexp.
       "[xyz]" matches the characters x, y, or z.       "[c-n]" matches any of the characters in the range c to n.       "[B-Pk-y]" matches any of the characters in the ranges B to P and k to y       "[a-z0-9]" matches any lowercase letter or any digit.       "[^b-d]" matches all characters except those in the range b to d.                (This is an instance of ^ negating or inverting the meaning of                the following regexp, taking on a role similar to ! in a different                context.)       Combined sequences of bracketed characters match common word       patterns.       "[Yy][Ee][Ss]" matches yes, Yes, YES, yEs, and so forth.       "[0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][0-9][0-9]" matches any       Social Security number.                                      
  • The backslash \ escapes a specialcharacter, which means thatcharacter gets interpreted literally.
     A "\$" reverts back to its literal meaning of "$", rather than its     regexp meaning of end-of-line. Likewise a "\\" has the literal meaning     of "\".
  • ( ) - treats the expression between ( and ) as a group. Also, saves the characters matched by the expression into temporary holding areas. Up to nine patternmatches can be saved ina single regular expression. They can be referenced as \1 through \9. On the shell command line or in scripts, the ( and ) metacharacters have be escaped like this: \( \).
  • | - “or” two conditions together
       "him|her" matches "it belongs to him" and "it belongs to her"       "(Memo|Report)20.\.txt" matches Memo201.txt, Report20a.txt, and       Report209.txt; note use of grouping ().  Certain applications       require the parens () to be escaped:  \( and \)       $ w | grep "jchung\|clayton" # Note the "\|" in the grep regexp.

Extended regular expressions

  • Used in egrep, awk, and Perl
  • The question mark ? matches zero oroneof the previous regexp. It is generally used for matching single characters.
     im?ing matches swiing, swiming, but not swimming
  • The plus + matches one or more of the previous regexp. It servesa role similar to the *,but doesnot match zero occurrences.
     9+ matches 9, 99, 999, but not 88
  • {i}, {i,j} - match a specific numberof instances or instances withina rangeof the precedingcharacter.
    • If used on the command line the {} chars may have to be escaped with “\”: \{ \}
       A[0-9]{3} matches "A" followed by exactly 3 digits (A123 but not       A1234).       [0-9]{4,6} matches any sequence of 4, 5 or 6 digits

Simple regexp examples using the %s (search and replace) command in vi

    :%s/  */ /g          Change 1 or more spaces into a single space.    :%s/ *$//            Remove all spaces from the end of the line.    :%s/^/ /             Insert a space at the beginning of every line.    :%s/^[0-9][0-9]* //  Remove all numbers at the beginning of a line.    :%s/b[aeio]g/bug/g   Change all occurences of bag, beg, big, and bog, to                         bug.

Medium regexp example using search and replace in vi

  • Change all instances of foo(a,b,c) to foo(b,a,c). wherea, b, and c can beany parameters supplied to foo(). That is, we must be able to make changes like the following:
 Before                   After ------                   ----- foo(10,7,2)              foo(7,10,2) foo(x+13,y-2,10)         foo(y-2,x+13,10) foo(bar(8),x+y+z,5)      foo(x+y+z,bar(8),5) The following substitution command will do the trick: :%s/foo(\([^,]*\),\([^,]*\),\([^)]*\))/foo(\2,\1,\3)/g [^,]  means any character which is not a comma. [^,]*  means 0 or more characters which are not commas. \([^,]*\)  using grouping \( )\, tags the non-comma characters as \1 for use in the replacement part of the command. \([^,]*\),  means that we must match 0 or more non-comma characters which are followed by a comma. The non-comma characters are tagged. foo(\([^,]*\),  translates to "after you find foo(, tag all characters up to the next comma as \1".

Lab Activity

1. Download http://rockhopper.monmouth.edu/~jchung/cs370/fa10/files/roster.fa06 and http://rockhopper.monmouth.edu/~jchung/cs370/fa10/files/roster.fa08 . Put the contentsof roster.* intoa singleroster file. Using search and replace invi ora vi-like editor that understands regular expressions, convert the rawroster file toa list with the following format:

        Lastname-Firstname:StudentID        

The list would be even better if Lastname and Firstname were both lower case, like this:

        lastname-firstname:StudentID

============================================================================

echo "111(222)333"|sed 's/(\(.*\))/\1\1/'    返回如下

111222222333

解读,这其中圆括号扮演定义一个区域的含义,当然前提是反斜杠标记的括号;

对于以上的用法:(\(.*\))/ 匹配(222)这个部分,并且将222作为区域,并且是区域1,如果后面还有区域则依次为2、3等,接着/\1\1/代表将(222)替换为两个区域1的内容,就是222222;

=======================================================

  1. 作者:吕晓波
  2. 出处:不详

  3.     如果我们问那些UNIX系统的爱好者他们最喜欢什么,答案除了稳定的系统和可以远程启动之外,十有八九的人会提到正则表达式;如果我们再问他们最头痛的是什么,可能除了复杂的进程控制和安装过程之外,还会是正则表达式。那么正则表达式到底是什么?如何才能真正的掌握正则表达式并正确的加以灵活运用?本文将就此展开介绍,希望能够对那些渴望了解和掌握正则表达式的读者有所助益。

  4. 入门简介
  5.   简单的说,正则表达式是一种可以用于模式匹配和替换的强有力的工具。我们可以在几乎所有的基于UNIX系统的工具中找到正则表达式的身影,例如,vi编辑器,Perl或PHP脚本语言,以及awk或sed shell程序等。此外,象JavaScript这种客户端的脚本语言也提供了对正则表达式的支持。由此可见,正则表达式已经超出了某种语言或某个系统的局限,成为人们广为接受的概念和功能。
  6.   正则表达式可以让用户通过使用一系列的特殊字符构建匹配模式,然后把匹配模式与数据文件、程序输入以及WEB页面的表单输入等目标对象进行比较,根据比较对象中是否包含匹配模式,执行相应的程序。
  7.   举例来说,正则表达式的一个最为普遍的应用就是用于验证用户在线输入的邮件地址的格式是否正确。如果通过正则表达式验证用户邮件地址的格式正确,用户所填写的表单信息将会被正常处理;反之,如果用户输入的邮件地址与正则表达的模式不匹配,将会弹出提示信息,要求用户重新输入正确的邮件地址。由此可见正则表达式在WEB应用的逻辑判断中具有举足轻重的作用。

  8. 基本语法
  9.   在对正则表达式的功能和作用有了初步的了解之后,我们就来具体看一下正则表达式的语法格式。
  10.   正则表达式的形式一般如下:
  11.   /love/
  12.   其中位于“/”定界符之间的部分就是将要在目标对象中进行匹配的模式。用户只要把希望查找匹配对象的模式内容放入“/”定界符之间即可。为了能够使用户更加灵活的定制模式内容,正则表达式提供了专门的“元字符”。所谓元字符就是指那些在正则表达式中具有特殊意义的专用字符,可以用来规定其前导字符(即位于元字符前面的字符)在目标对象中的出现模式。
  13.   较为常用的元字符包括: “+”, “*”,以及 “?”。其中,“+”元字符规定其前导字符必须在目标对象中连续出现一次或多次,“*”元字符规定其前导字符必须在目标对象中出现零次或连续多次,而“?”元字符规定其前导对象必须在目标对象中连续出现零次或一次。
  14.   下面,就让我们来看一下正则表达式元字符的具体应用。
  15.   /fo+/
  16.   因为上述正则表达式中包含“+”元字符,表示可以与目标对象中的 “fool”, “fo”, 或者 “football”等在字母f后面连续出现一个或多个字母o的字符串相匹配。
  17.   /eg*/
  18.   因为上述正则表达式中包含“*”元字符,表示可以与目标对象中的 “easy”, “ego”, 或者 “egg”等在字母e后面连续出现零个或多个字母g的字符串相匹配。
  19.   /Wil?/
  20.   因为上述正则表达式中包含“?”元字符,表示可以与目标对象中的 “Win”, 或者 “Wilson”,等在字母i后面连续出现零个或一个字母l的字符串相匹配。
  21.   除了元字符之外,用户还可以精确指定模式在匹配对象中出现的频率。例如,
  22.   /jim/
  23.   上述正则表达式规定字符m可以在匹配对象中连续出现2-6次,因此,上述正则表达式可以同jimmy或jimmmmmy等字符串相匹配。
  24.   在对如何使用正则表达式有了初步了解之后,我们来看一下其它几个重要的元字符的使用方式。
  25.   \s:用于匹配单个空格符,包括tab键和换行符;
  26.   \S:用于匹配除单个空格符之外的所有字符;
  27.   \d:用于匹配从0到9的数字;
  28.   \w:用于匹配字母,数字或下划线字符;
  29.   \W:用于匹配所有与\w不匹配的字符;
  30.   . :用于匹配除换行符之外的所有字符。
  31.   (说明:我们可以把\s和\S以及\w和\W看作互为逆运算)
  32.   下面,我们就通过实例看一下如何在正则表达式中使用上述元字符。
  33.   /\s+/
  34.   上述正则表达式可以用于匹配目标对象中的一个或多个空格字符。
  35.   /\d000/
  36.   如果我们手中有一份复杂的财务报表,那么我们可以通过上述正则表达式轻而易举的查找到所有总额达千元的款项。
  37.   除了我们以上所介绍的元字符之外,正则表达式中还具有另外一种较为独特的专用字符,即定位符。定位符用于规定匹配模式在目标对象中的出现位置。
  38.   较为常用的定位符包括: “^”, “$”, “\b” 以及 “\B”。其中,“^”定位符规定匹配模式必须出现在目标字符串的开头,“$”定位符规定匹配模式必须出现在目标对象的结尾,\b定位符规定匹配模式必须出现在目标字符串的开头或结尾的两个边界之一,而“\B”定位符则规定匹配对象必须位于目标字符串的开头和结尾两个边界之内,即匹配对象既不能作为目标字符串的开头,也不能作为目标字符串的结尾。同样,我们也可以把“^”和“$”以及“\b”和“\B”看作是互为逆运算的两组定位符。举例来说:
  39.   /^hell/
  40.   因为上述正则表达式中包含“^”定位符,所以可以与目标对象中以 “hell”, “hello”或 “hellhound”开头的字符串相匹配。
  41.   /ar$/
  42.   因为上述正则表达式中包含“$”定位符,所以可以与目标对象中以 “car”, “bar”或 “ar” 结尾的字符串相匹配。
  43.   /\bbom/
  44.   因为上述正则表达式模式以“\b”定位符开头,所以可以与目标对象中以 “bomb”, 或 “bom”开头的字符串相匹配。
  45.   /man\b/
  46.   因为上述正则表达式模式以“\b”定位符结尾,所以可以与目标对象中以 “human”, “woman”或 “man”结尾的字符串相匹配。
  47.   为了能够方便用户更加灵活的设定匹配模式,正则表达式允许使用者在匹配模式中指定某一个范围而不局限于具体的字符。例如:
  48.   /[A-Z]/
  49.   上述正则表达式将会与从A到Z范围内任何一个大写字母相匹配。
  50.   /[a-z]/
  51.   上述正则表达式将会与从a到z范围内任何一个小写字母相匹配。
  52.   /[0-9]/
  53.   上述正则表达式将会与从0到9范围内任何一个数字相匹配。
  54.   /([a-z][A-Z][0-9])+/
  55.   上述正则表达式将会与任何由字母和数字组成的字符串,如 “aB0” 等相匹配。这里需要提醒用户注意的一点就是可以在正则表达式中使用 “()” 把字符串组合在一起。“()”符号包含的内容必须同时出现在目标对象中。因此,上述正则表达式将无法与诸如 “abc”等的字符串匹配,因为“abc”中的最后一个字符为字母而非数字。
  56.   如果我们希望在正则表达式中实现类似编程逻辑中的“或”运算,在多个不同的模式中任选一个进行匹配的话,可以使用管道符 “|”。例如:
  57.   /to|too|2/
  58.   上述正则表达式将会与目标对象中的 “to”, “too”, 或 “2” 相匹配。
  59.   正则表达式中还有一个较为常用的运算符,即否定符 “[^]”。与我们前文所介绍的定位符 “^” 不同,否定符 “[^]”规定目标对象中不能存在模式中所规定的字符串。例如:
  60.   /[^A-C]/
  61.   上述字符串将会与目标对象中除A,B,和C之外的任何字符相匹配。一般来说,当“^”出现在 “[]”内时就被视做否定运算符;而当“^”位于“[]”之外,或没有“[]”时,则应当被视做定位符。
  62.   最后,当用户需要在正则表达式的模式中加入元字符,并查找其匹配对象时,可以使用转义符“\”。例如:
  63.   /Th\*/
  64.   上述正则表达式将会与目标对象中的“Th*”而非“The”等相匹配。

  65. 使用实例

  66.   在对正则表达式有了较为全面的了解之后,我们就来看一下如何在Perl,PHP,以及JavaScript中使用正则表达式。

  67.   通常,Perl中正则表达式的使用格式如下:

  68.   operator / regular-expression / string-to-replace / modifiers

  69.   运算符一项可以是m或s,分别代表匹配运算和替换运算。

  70.   其中,正则表达式一项是将要进行匹配或替换操作的模式,可以由任意字符,元字符,或定位符等组成。替换字符串一项是使用s运算符时,对查找到的模式匹配对象进行替换的字符串。最后的参数项用来控制不同的匹配或替换方式。例如:

  71.   s/geed/good/

  72.   将会在目标对象中查找第一个出现的geed字串,并将其替换为good。如果我们希望在目标对象的全局范围内执行多次查找—替换操作的话,可以使用参数 “g”,即s/love/lust/g。

  73.   此外,如果我们不需要限制匹配的大小写形式的话,可以使用参数 “i ”。例如,

  74.   m/JewEL/i

  75.   上述正则表达式将会与目标对象中的jewel,Jewel,或JEWEL相匹配。

  76.   在Perl中,使用专门的运算符“=~”指定正则表达式的匹配对象。例如:

  77.   $flag =~ s/abc/ABC/

  78.   上述正则表达式将会把变量$flag中的字串abc替换为ABC。

  79.   下面,我们就在Perl程序中加入正则表达式,验证用户邮件地址格式的有效性。代码如下:
  80.     --------------------------------------------------------
  81.   #!/usr/bin/perl
  82.   # get input
  83.   print “What's your email address?\n”;
  84.   $email = <STDIN>
  85.   chomp($email);
  86.   # match and display result
  87.   if($email =~ /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/)
  88.   {
  89.   print(“Your email address is correct!\n”);
  90.   }
  91.   else
  92.    {
  93.     print(“Please try again!\n”);
  94.    }
  95.     --------------------------------------------------------

  96.   如果用户更偏爱PHP的话,可以使用ereg()函数进行模式匹配操作。ereg()函数的使用格式如下:
  97.    ereg(pattern, string)

  98.   其中,pattern代表正则表达式的模式,而string则是执行查找替换操作的目标对象。同样是验证邮件地址,使用PHP编写的程序代码如下:

  99.     --------------------------------------------------------
  100.   <?php
  101.    if (ereg(“^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+”,$email))
  102.     { echo “Your email address is correct!”;}
  103.    else
  104.     { echo “Please try again!”;}
  105.    ?>
  106.     --------------------------------------------------------

  107.   最后,我们在来看一下JavaScript。JavaScript 1.2中带有一个功能强大的RegExp()对象,可以用来进行正则表达式的匹配操作。其中的test()方法可以检验目标对象中是否包含匹配模式,并相应的返回true或false。

  108.   我们可以使用JavaScript编写以下脚本,验证用户输入的邮件地址的有效性。

  109.     --------------------------------------------------------
  110.   <html>
  111.    <head>
  112.     <script language="Javascript1.2">
  113.      <!-- start hiding
  114.      function verifyAddress(obj)
  115.      {
  116.       var email = obj.email.value;
  117.       var pattern = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
  118.       flag = pattern.test(email);
  119.       if(flag)
  120.       {
  121.        alert(“Your email address is correct!”);
  122.        return true;
  123.       }
  124.       else
  125.        {
  126.         alert(“Please try again!”);
  127.         return false;
  128.         }
  129.       }
  130.      // stop hiding -->
  131.     </script>
  132.    </head>
  133.    <body>
  134.    <form onSubmit="return verifyAddress(this);">
  135.    <input name="email" type="text">
  136.    <input type="submit">
  137.    </form>
  138.   </body>
  139.  </html>
  140.     --------------------------------------------------------
复制代码
================================================================
根据这坛里的链接找到的台湾出品的几篇好贴,感觉很不错,又受到了一次基础培训和巩固复习.所以收藏后也共享给大家,谢谢!

Regular Expression 简介

中央研究院计算中心
ASPAC 计划
aspac@phi.sinica.edu.tw
技术报告: 94019
1995 年 2 月 9 日
Version : 1.0


版权声明

目录
Why Regular Expression
组成 Regular Expression 的元素
使用 Regular Expression 时的注意事项
范 例
Appendix : Test using Regular Expression in various environments
HP-UX
Sun Solaris 2.X
AIX 3.2.5
GNU Tools

Why Regular Expression
Regular Expression 是一种字符串表达的方式. 使用者可使用一个简短的 Regular Expression 来表示 〝具有某特征〞 或者 〝复杂难以描述〞的所有字符串. 而日常数据处理中, 最常进行的工作是『从档案中找出具有某特征的字符串, 再加以处理(打印,置换, 计算...)』. 此时, Regular Expression 便可派上用场. 使用一个简短的 Regular Expression 便可完全指定需要加以处理的资料 , 避免反复判断找寻的困扰. 譬如 :
若使用 MS-DOS 中文字编辑器 edit 的找寻功能, 可来 找出档案中所有的 ``prg1.c''; 但 edit 却无法一次同 时找寻字符串``prg1.c''、``prg2.c'' ... 或 ``prg8.c''; 必需 反复执行八次找寻的动作.

可是在 UNIX 中的 vi , 使用一个 Regular Expression `` prg[0-8]\.c'' 便可同时表示上述八个字符串, 如此一次就可找出指定的所有字符串.

可见 Regular Expression 确实十分便利. 然而, MS-DOS 下许多工具的设计并不支持解读 Regular Expression. 但 UNIX 环境下除了 vi 外, 还有许多工具都接受 Regular Expression, 如 : grep、sed、awk、csplit... . 使用这些工具时, 便可应用 Regular Expression 来指定欲找寻的字符串; 并可配合这些工具的其它功能将找寻到的数据进一步地加以处理.

Regular Expression 的特色是简短且表达力强. 它所表达的可以是某一特定的字符串, 也可以是具有某一共同特征的"所有"字符串(如上例). Regular Expression 中定义了一组特殊字符, 它们代表着某些特别的意义; 使用者可藉这些特殊字符来表示字符串的下列特征 :


描述组成字符串的元素(components) : 例 如 : Regular Expression ``[Tt]he'' 代表字符串 ``The'' 或 ``the''.
限制字符串出现的位置 : 例 如 : Regular Expression ``^The'' 代表『出现于行首』的字符串 ``The''.
由于 Regular Expression 具有极佳的字符串表示能力. 往后, 读者若能多利用 UNIX 上接受 Regular Expression 的工具, 且灵活应用 Regular Expression; 则可避免撰写程序进行复杂字符串判断(parsing) 的麻烦. 如此, 才能真正发挥各工具的的功能, 减轻数据处理时的负担, 并增加数据处理的效率.



--------------------------------------------------------------------------------


Note 1
UNIX中定义了数种字符串表达方式, Regular Expression 及 Extended Regular Expression 是常见的二种. 另一种是使用于Shell命令列, 将参数展开}(expand)成文件名称的"attern Matching Notation", 这种表示法与 Regular Expressions 的语法差异较大, 甚至有数项用法相左, 故位未列入本文讨论以免读者混淆.


组成 Regular Expression 的元素
Regular Expression 是由普通字符、及一组具有特殊意义 的字符所构成. 本节主要介绍各种特殊字符所代表的意义及 其用法. 读者学习时应留心 : 有时, 同一特殊字符, 会因出 现在字符串中不同的位置或连接其它特殊字符, 而有不同的意义. 本文中为有别于一般的字符串, 所有 Regular Expression 都以粗体字体表示, 且加注``Regexp''于其前方.
组成 Regular Expression 的元素及所代表的意义如下 :


[普通字符] 除了``.''、``[''、``]''、``*''、``+''、``?''、 ``|''、``^''、``$''、``{''、``}''、``\''、 ``<''、``>''、``(''、``)'' 外之所有字符.
由普通字符所组成的 Regular Expression 其意义与原字符串字面意义相同. 例如 :


普通字符``A''也可当成一个 Regular Expression. Regexp `` A'' 与一般字符``A''代表相同的意义.
Regexp `` the'' 与一般字符串``the''代表相同的意义.
[ .] Metacharacter 用以代表任意一个字符. 须留心 UNIX Shell 中使用``?''表示任意一个字符, 使用``*''代表任意长 度的字符串(这是另一种称为 ``Pattern Matching Notation'' 的字符串表示法). Regular Expression 中则使用`` .'' 来代表``一个''任意字符(注 意: 并非任意长度的字符串). 而 Regular Expression 中`` *''另有 其它涵意, 并不代表任意长度的字符串. 例如

Regexp `` .'' 可用以代表任意一个字符. 如 ``A''、``1''、``+''、...
Regexp `` ...'' 则代表一个由任意3个字符所的字符串. 譬如 ``123''、``abc''、``# 1''、...
[ ^] 限制字符串必须出现于行首. (用法见下例)
[ $] 限制字符串必须出现于行末.
[例如 :] Regexp `` ^The'' 用以表示所有出现于行首的字符串``The''. Regexp `` The$'' 用以表示所有出现于行末的字符串``The''. Regexp `` ^The$'' 则用以表示一个仅含字符串``The''的数据列. Regexp `` ^$'' 表示一个空白的数据列(行首与行尾之间未存在任一字符).

[ \] 将特殊字符还原成字面意义的字符. Regular Expression 中 特殊字符 将被解释成特定的意义. 若要表示特殊字符的字面(literal meaning) 意义时, 在 特殊字符之前加上 ``\'' 即可.

[例如 :] 使用 Regular Expression 来表示字符串``a.out''时, 不可写成 Regexp `` a.out''. 因为`` .''在 Regular Expression 中是特殊字符, 表示任一字符.
可合乎(match) Regexp `` a.out'' 的字符串将不只 ``a.out'' 一个; 字符串``a2out'',``a3out'', ``aaout''... 都合于 Regexp `` a.out''.
正确的表示法应为 : Regexp `` a\.out''

`` \'' 在 Regular Expression 中的另一个意 义是当成 Escape character.

[例如 :] `` \t'' 用以表示 tab. `` \n'' 表示换行符号.
[...] 『字符集合』, 用以表示两中括号间 所有的字符当中的任一个.
[例如 : ] Regexp `` [123]'' 可用以表示字符 ``1''、``2'' 或 ``3''. Regexp `` [Tt]'' 可用以表示字符 ``T'' 或 ``t''. 所以, Regexp " [Tt]he" 表示字符串 "The" 或 "the". (注意 : 一个字符集合仅代表``一个''字符.)
使用时, 需留心字符集合 [ ] 内不可随意留空白.

例如 : Regexp `` [ Tt ]'' 中括号内有空格符, 故除了可用 以表示字符``T''或``t''", 也可代表一个 `` ''(空格符).
- 字符集合中可使用 `` -'' 来指定字符的区间, 其用法如下:
Regexp `` [0-9]'' 等于 Regexp `` [0123456789]'' 用以表示任意 "一个" 阿拉伯数字. 同理 Regexp `` [A-Z]'' 用以表示任意 "一个" 大写英文字母.

但应留心 :


Regexp " [0-9a-z]" 并不等于 Regexp " [0-9][a-z]"; 前者表示一个字符(阿拉伯数字或小写英文字母), 后者表示二个字符.
Regexp " [-9]" 或 " [9-]" 仅用以代表字符 ``9''或 ``-''.
[ [\^{}... ]] 使用 [\^{...]} 产生字符集合的补集(complement set). 其用法如下 :

Regexp `` [^M]'' 用以表示除字符``M''外的``一个''任意字符
字符集合 `` [Tt]''表示字符 ``T'' 或 ``t''. 若要指定 ``T'' 或 ``t'' 之外的任一个字符, 可用Regexp `` [^Tt]'' 表示.
Regexp `` [^a-zA-Z]''表示英文字母之外的任一个字符.
需留心 `` ^''之位置; `` ^'' 必须紧接于 `` ['' 之后, 才代表字符集合的补集.

[例如 :] Regexp `` [0-9^]'' 表示一个阿拉伯数字或字符 `` ^'', 并非代表阿伯数字外的任意字符.
* 用以形容其前的字符或字符集合可重复任意次数的特殊字符.
`` *'' 形容它前方之字符(或字符集合)可出现 1 次或多次, 或不出现. 例如 :

Regexp ``ab*'' 中, `` *'' 形容它前方的字符 ``b'' 可出现 1 次或多次, 或不出现. 所以, Regexp ``ab*'' 可表示字符串 ``a''、``ab''、``abb''、 ``abbb''、...
Regexp `` T[0-9]*\.c'' 中, 使用 `` *'' 形容其前的字符集合 `` [0-9]''(一个阿拉伯数字)出现的次数 : 可为 0 次或多次.
故 Regexp `` T[0-9]*\.c''可用以表示 ``T.c''、``T0.c''、 ``T1.c''、``T2.c''、...、``T9.c''、``T00.c''、``T01.c''、``T02.c''、...、 ``T09.c''、``T10.c''、...``T99.c''、``T000.c''、...


[ \<] `` \< Regexp'' 表示一个出现于"前缀"且又合于(match)该 Regexp 的字符串 (用法见下例).
[ \>] ``Regexp \>'' 表示一个出现于"字末"且又合于(match)该 Regexp 的字符串.
这里所谓的``字(word)''系指被 tab、逗点、句点或空格符(space) 所分隔开的字符串.
[例如 :]
资料 ``One is red, and the other is white.'' 中 字符串 ``One'', ``is'', ``red'', ``and'', ``the'', ``other'', ``is'', ``white'' 便是所谓的 "字(word)". 而该资料列中,
合于 Regexp ``[Tt]he''的字符串如下(粗体字标示)
``One is red, and the other is white.''
合于 Regexp `` \<[Tt]he\>''却仅有(粗体字标示)
``One is red, and the other is white.''
因同时使用`` \<''及`` \>'' 限制合于 Regexp `` [Tt]he''的字符串, 必须紧接于前缀及字尾之间; 故 ``other''中的子字符串 ``the''并不合于这个 Regular Expression.

[注 :] \<, \> 这二个特殊字符, 并不是很通用. 请参考 Appendix A 中的附表.
\( ... )\ 于 Regular Expression 中使用 `` \(''``{ \)}''来括住一部分的 Regular Expression; 其后可用 `` \1'''来表示第一次被`` \('' `` \)'' 括住的部份. 若 Regular Expression 中使用了数次`` \('' `` \)'' 来括住不同的部分, 则依次使用 ``\1'', `` \2'', `` \3'' ,...(最多可用到 `` \9'')来 表示之前括住的 Regular Expression. 其用法如下 :

[用法一.]
例如: 欲表示像``aa'',``bb'',``cc'',...``zz'' 等字符串.
使用 Regexp `` [a-z]''则表示任一个小写的英文字母.
使用 Regexp `` [a-z][a-z]''则表示二个任意的小写英文字母. 它除表示 ``aa'',``bb'',``cc'',...``zz''等字符串外, 也可表示``ab'', ``ac'',``ad'',...等字符串(这不是题意所要求的字符串).
这时可以`` \('' `` \)'' 来括住第一个 `` [a-z]'' (Regular Expression 解译的程序, 会暂时记录实际找寻 到的英文字母). 之后, 便可以 Regexp ``\1'' 来指定适才被记 录下的英文字母即为所要找寻字符串的第二个字符. 故正确的表示法如下 :
Regexp `` \([a-z]\)\1''

例如 : 欲表示像 ``789w987'', ``abcwcba'', ``theweht'',....等具对称性 的字符串.(该字符串的特征是 ``w''之前后三个字符相互对称) 该类字符串的表示法如 下 :
Regexp `` \(.\)\(.\)\(.\)w\3\2\1" Regexp中`` .''表示任意一个字符. 因字符``w''之前出现的三个字符并无 任何限制, 故可用 `` ...''表之. 但每个`` .''分别用 `` \('',`` \)'' 括住, 之后便可使用 `` \1'', `` \2'', `` \3'' 分别代表将来实际匹配到的前三个字符.


用法二. 进行字符串找寻并置换(Replace)时, 若将被置入的新字符串不是一个固定的字符串, 与被找到的原字符串有关时(见下例说明). 此时, 可先以 \( \)来括住一部分的Regular Expression; 再于将被新置入的字符串中使用`` \1'', `` \2'',... 来表示当时被找到的字符串(或其子字符串).
例 : 欲找出档案中具有 ``prog12.c'', ``prog9.c'', ``prog832.c'',... 等式样的字符串, 并将其置换成(以上列三个字符串为例) ``[ note 12]'', ``[ note 9]'', ``[ note 832]''. 在这例子中, 因事先不知道所找寻到的字符串(prog数字.c)中的 数字 为何, 故无法事先决定应换成什么新字符串. 合于本例所要找寻的字符串其 Regular Expression 为 :
Regexp `` prog[0-9][0-9]*\.c'' 上式中 `` [0-9][0-9]*'' 表一位或一位以上的阿拉伯数字, 因 执行前并不知道该部分实际会匹配什么数值, 故找到的字符串将来应置换 成什么, 事前无法指定. 这情况, 也可用`` \('',`` \)'' 来括住 `` [0-9][0-9]* '', 在置换的新字符串中再以 \1 表示找寻时实际匹配到的数字.

读者可编辑一数据文件, 再以sed执行下列命令, 观察其执行结果.

$sed -e 's/ prog\([0-9][0-9]*\)\.c/[ note \1]/g' 资料文件名

\{ 数字, 数字\} 一种于 Regular Expression 中形容其前的字符或字符 集合出现次数的表示法. 其型态与用法如下 :

\{下限数字, 上限数字\}
例如 : Regexp "[0-9]\{2,4\}"用以表示2到4位的阿拉伯数字.
{ 数字}
例如 : Regexp `` ax\{99\}'' 用以表示一个 ``a'' 之后接上99个 ``x'' 所组成的字符串.
\{下限数字, \} 例如 : Regexp `` ax\{2,\}'' 用以表示一个 ``a'' 之后接上2个或更多的 ``x''所组成的字符串.
+ 形容其前的字符或字符集合出现一次或一次以上(注三).
例如 : Regexp `` [0-9]+'' 用以表示一位或一位以上的数字.

? 形容其前的字符或字符集合可出现一次或不出现(注三).

[例如 :] Regexp ``[+-]?[0-9]+'' 表示数字(一位以上)之前可出现一个正负号 或不出现正负号.
[ (...)] 用以括住一群字符,且将之视成一个group(见下面说明)(注三)
例如 :
Regexp `` 12+'' 表示字符串 "12","122","1222","12222",...
Regexp `` (12)+'' 表示字符串 "12","1212","1212","1212"....

上式中字符串 ``12''以( )括住,整个视为一个group, 故被重复符号``+'' 所形容的是``12''而非 ``2'', 重复出现的也是 ``12''.

| 表示逻辑上的 "or" (注三)
例如 : Regexp `` Oranges?|apples?|water'' 可用以表示字符串``Orange'', ``Oranges''
或 ``apple'', ``apples''
或 ``water''

注三 : 上列 + , ?, (...), | 等用法, 为 Extended Regular Expression 中新增列的用法. awk 及 egrep 中所使用的 Regular Expression 即为 Extended Regular Expression. 但 vi, sed, grep,...等软件中并无这些用法.
& ``&''并非 Regular Expression 中的特殊字符. 但以 Regular Expression 进行字符串找寻置换(Replace)时, 常会用到 ``\&''. \ 在许多 Unix tool 中, 当 ``\&''出现在『将被置入的新字符串』时, 它用以表示 ``实际被找到合于所指定的 Regular Expression 的字符串'' (见下例说明)
例如 : 找出档案中所有合乎 Regexp ``a[0-9]*\.c'' 的字符串, 并在其前后加上小 括号.依题意要求, 档案中所有如 ``a12.c'', ``a932.c'', ``a45.c'' ,...等字符串都应置换为 ``(a12.c)'', ``(a932.c)'', ``(a45.c)'',.. . . 遇到这情况,可令『将被置入的新字符串』为 `` (&'' 此时, ``&''便是用来表示实际上被找到合于 Regexp ``a[0-9]*\.c'' 的字符串.
下列是使用 UNIX 上不同的工具, 来处理本例要求的字符串置换.

vi 以 vi 编辑该档案,并在 vi 命令输入模式下输入
: s/a[0-9]*\.c/(&/g
sed 执行如下命令 ( $ 表 Shell 命令列的提示符号 )
$ sed -e 's/a[0-9]*\.c/ (&/g' 数据文件名称
awk 执行如下命令 ( $ 表 Shell 命令列的提示符号 )
$ awk '{ gsub(/a[0-9]*\.c/, "(&"; print }' 数据文件名称

--------------------------------------------------------------------------------


Note 2:
上列字符在 Regular Expression 中代表特殊意义, 称之为 特殊字符. 但 Unix 中不同的指令对 Regular Expression 的解释能力不尽相同, 故对特殊字符也有不同的认定. 请参考尾页附表.


使用 Regular Expression 时的注意事项
学习 Regular Expression 除了应了解其中特殊字符所代表的意义外; 在实际应用时, 也有一些应该注意的事项. 倘若忽略了这些特点, 往往会 造成字符串无法正确比对, 而导至结果错误. 本节除了介绍这些应予留心的事 项外, 也提供各软件在解读 Regular Expression, 进行字符串比对时所依据的 二项重要原则.

接受 Regular Expression 的指令或工具, 它们找寻字符串时系按照下列二原则:

由左往右进行字符串找寻.
尽可能寻找最长且合于所指定 Regular Expression 的字符串.
例如 : 应用 Regexp `` a.*b''(代表以"a"开头以"b"结尾 的任意字符串),于数据列 ``12 3ab0aab4 56'' 中找寻合于该条件 的字符串.
该资料列中合于 Regexp `` a.*b'' 的字符串有 ``ab'', ``aab'', ``ab0aab''. 但按上列二原则「由左往右找, 且尽可能寻 找最长的字符串」 实际上被找到的字符串将为 ``ab0aab''.


Regular Expression 有许多不同的版本 UNIX 中不同的指令对同一个 Regular Expression 可能会有不同的解释. 原因是这些指令无法完全解释前节所述 Regular Expression 中所有的特殊字符. 这就是所谓 "Regular Expression 有许多不同的版本"

例如 : egrep 中对 Regexp `` an?'' 解释成字符串 ``a'' 或 ``an''. 但 vi 中对 Regexp `` an?'' 只解释成字符串 ``an?''. 因为 vi 中并不把 `` ?'' 当成 Regular Expression 的特殊字原解释.
Appendix A 附表 中列出 UNIX 中常用的指令及它所接受的 Regular Expression 特殊字符.

勿将Shell上所使用的字符串表示法(Pattern Matching Notation) 与 Regular Expression 混淆.
Regexp `` a*'' 用以表示一个完全由字符 "a" 所组成的任意长度字符串. 但在 Shell 命令列上执行 ``ls a*'', 却会列出目前工作目录下所有以 "a" 开头的档案与子目录.两者对 ``a*'' 的解释并不相同. 因为 Shell 所接受的是另一种名为 ``Pattern Matching Notation'' 的表示法, 两者并不相同请勿混淆.

在含有中文之文字文件中, 使用 Regular Expression 进行字符串找寻时, 可能会发生错误.
譬如 : 找寻左大括号"{", 结果中文的"程"也被找出. 这并非 Regular Expression 出了错误. 因每个中文字都是由 2 个 bytes 组成, 而中文``程''字的后一个 byte 恰 被解释成``{''.所以除非所使用的指令有自动避开中文字的功能, 否则中文字的后一个 byte 被误判的机率并不低. 故读者在含有中文文字的档案中, 进行字符串找寻并置换时, 最好是逐次确认后再行置换.

并非所有软件都接受 Regular Expression(有解读 Regular Expression 的能力). 一般而言,就算某软件(工具)可接受 Regular Expression , 它也并非把所有的字 串或参数当成 Regular Expression 解释. 读者使用 Regular Expression 时, 应先确定该软件会把该些字符串当成 Regular Expression 解释(可翻查其 manual page), 如此才可获得正确的结果.

范 例
本节列出数个 Regular Expression 的应用简例, 供读者参考. 由这些范例中, 读者可一窥实际应用时, 如何藉由 Regular Expression 来表达字符串, 来完成 某些目的. 至于各指令像 vi, sed, awk, ...中之语法说明已非本文所能涵盖, 读者请自行参考相关书籍.

a. 将档案中所有字符串 ``Regular Expression'' 或 ``Regular expression'' 换成 ``Regexp''.
以 vi 编辑该档案, 并在 vi 命令输入模式下执行 :
:1,$ s/ Regular [Ee]xpression/Regexp/g
b. 将档案中所有具 ``ddd-dddd'' 特征的字符串(d表阿拉伯数字)之前插入字符串 ``Tel :''.
以 vi 编辑该档案, 并在, vi 命令输入模式下执行 :
:1,$ s/[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]/Tel:&/g
说明 : `` &'' 代表执行时实际合于该 Regular Expression 的字符串.
c. 将档案中所有俱有 `` program数字.c'' 特征的字符串换成 ``test数字.f''.
解法 : 以vi编辑该档案, 并在vi命令输入mode下执行 :
:1,$ s/ program\([0-9][0-9]**\)\.c/test\1.f/g
说明 : Regexp `` [0-9][0-9]*'' 表示一位或一位以上的阿拉伯数字. `` \1'' 被找到的字符串中的数值部分. (被\(...\)括住的部分).
d. 将档案中第5-13行, 整个区域往右移5格(空格符).
解法 : 以vi编辑该档案, 并在vi命令输入mode下执行
:5,13 s/ .*/ &/

说明 : Regexp `` .*" 用以 match 整个数据列(之后以&表之). 并用 `` &''(5个空白及原先之资料列)取代该列资料.
e. 将上例档案中的数据列(5-13行), 往左移回3格.
解法 : 以vi编辑该档案, 并在vi命令输入mode下执行
:5,13 s/ \^ ///

说明 : 将行首的三个空格符换成空字符串.
f. 试从一个档案的全名中分离出其路径及文件名.

解法 : 编辑如下的script并取名为 ``sepname''
awk '
BEGIN {
match( ARGV[1], /.*\//)
print "path=", substr(ARGV[1], 1 ,RLENGTH-1)
print "name=", name = substr(ARGV[1], RLENGTH+1 )
} ' $1 }

执行 $ sepname /usr/local/bin/xdvi
结果印出 path= /usr/local/bin
name= xdvi
g. 将档案中以``From''或``from''为行首的数据打印出
执行 $ awk '/^[Ff]rom/ ' 数据文件文件名

h. 去除挡案中空白行
执行 $ sed -e "/ ^$/d"

后 语
虽然 Regular Expression 仅是一种字符串的表示方式, 但从上列的范例 中不难窥出, 配合接受 Regular Expression 的指令或工具, 其应用面 将远超出找寻字符串及置换字符串. 使用 Regular Expression 不仅扩大了 字符串的表达能力, 让使用者很容易进行字符串判断; 使数据处理的过程便 为更为迅速便利.



Appendix : Test using Regular Expression in various environments
HP-UX
下表列出测试 HP-UX Release 9.0 中常见的工具对 Regular Expression 中各种特殊字符的接受能力.


        ex        vi        sed        awk        grep        egrep        说明
.        *        *        *        *        *        *       
*        *        *        *        *        *        *       
^        *        *        *        *        *        *       
$        *        *        *        *        *        *       
\        *        *        *        *        *        *       
[ ]        *        *        *        *        *        *       
\( \)与\1...\9 合用(一)                        *                *                把\1...\9用于 Regular Expression 中
\( \)与\1...\9 合用(二)        *        *        *                -        -        把\1...\9用于欲置换的新字符串中
{重复次数}                        *                *               
{下限,上限}                        *                *               
{下限, }                        *                *               
\< \>        *        *                                       
+                                *                *       
?                                *                *       
|                                *                *       
( )                                *                *       
\        *        *        *        *        -        -       

* 表示该指令有解释这种特殊字符的能力.  
- 表示未测试该项功能.  


Sun Solaris 2.X
下表列出测试 Sun Solaris 2.x 中常见的工具对 Regular Expression 中各种特殊字符的接受能力

        ex        vi        sed        awk        grep        egrep        说明
.        *        *        *        *        *        *       
*        *        *        *        *        *        *       
^        *        *        *        *        *        *       
$        *        *        *        *        *        *       
\        *        *        *        *        *        *       
[ ]        *        *        *        *        *        *       
\( \)与\1...\9 合用(一)        *        *        *                *                把\1...\9用于 Regular Expression 中
\( \)与\1...\9 合用(二)        *        *        *                -        -        把\1...\9用于欲置换的新字符串中
{重复次数}        *        *        *                *               
{下限,上限}        *        *        *                *               
{下限, }        *        *        *                *               
\< \>        *        *        *                *               
+                                *                *       
?                                *                *       
|                                *                *       
( )                                *                *       
\        *        *        *        *        -        -       

* 表示该指令有解释这种特殊字符的能力.  
- 表示未测试该项功能.

AIX 3.2.5
下表列出测试 AIX 3.2.5 中常见的工具对 Regular Expression 中各种特殊字符的接受能力.

        ex        vi        sed        awk        grep        egrep        说明
.        *        *        *        *        *        *       
*        *        *        *        *        *        *       
^        *        *        *        *        *        *       
$        *        *        *        *        *        *       
\        *        *        *        *        *        *       
[ ]        *        *        *        *        *        *       
\( \)与\1...\9 合用(一)                        *                *                把\1...\9用于 Regular Expression 中
\( \)与\1...\9 合用(二)        *        *        *                -        -        把\1...\9用于欲置换的新字符串中
{重复次数}                        *                *               
{下限,上限}                        *                *               
{下限, }                        *                *               
\< \>        *        *                                       
+                                *                *       
?                                *                *       
|                                *                *       
( )                                *                *       
\        *        *        *        *        -        -       

* 表示该指令有解释这种特殊字符的能力.  
- 表示未测试该项功能.  



GNU Tools
下表列出测试 GNU 所提供的工具对 Regular Expression 中各种特殊字符的接受能力.

        sed        awk        grep -G        egrep -E        emacs        说明
.        *        *        *        *        *       
*        *        *        *        *        *       
^        *        *        *        *        *       
$        *        *        *        *        *       
\        *        *        *        *        *       
[ ]        *        *        *        *        *       
\( \)与\1...\9 合用(一)        *                *                        把\1...\9用于 Regular Expression 中
\( \)与\1...\9 合用(二)        *                -        -        *        把\1...\9用于欲置换的新字符串中
{重复次数}        *                *                       
{下限,上限}        *                *                       
{下限, }        *                *                       
\< \>        *                *        *        *       
+                *                *        *       
?                *                *        *       
|                *                *               
( )                *                *               
\        *        *        -        -               

* 表示该指令有解释这种特殊字符的能力.  
- 表示未测试该项功能.







0 0
原创粉丝点击