http://www.radsoftware.com.au/articles/regexlearnsyntax.aspx The basics - Finding text Text: Anna Jones and a friend went to lunch Regex: went Matches: Anna Jones and a friend went to lunch went Matching any character with dot Text: abc def ant cow Regex: a.. Matches: abc def ant cow abc ant Matching word characters Text: abc anaconda ant cow apple Regex: a\w\w Matches: abc anaconda ant cow apple abc ana ant app Backslash and an uppercase 'W' (\W) will match any non-word character. Matching white-space Text: "abc anaconda ant" Regex: a\w\w\s Matches: "abc " White-space is defined as the space character, new line (\n), form feed (\f), carriage return (\r), tab (\t) and vertical tab (\v). Be careful using \s as it can lead to unexpected behaviour by matching line breaks (\n and \r). Sometimes it is better to explicitly specify the characters to match instead of using \s. e.g. to match Tab and Space use [\t\0x0020] Matching digits Text: 123 12 843 8472 Regex: \d\d\d Matches: 123 12 843 8472 123 843 847 Matching sets of single characters Text: abc def ant cow Regex: [da].. Matches: abc def ant cow abc def ant Text: abc def ant cow Regex: [^da].. Matches: "bc " "ef " "nt " "cow" Matching ranges of characters Text: abc pen nda uml Regex: .[a-d]. Matches: abc pen nda uml abc nda Text: abc no 0aa i8i Regex: [a-z0-9]\w\w Matches: abc no 0aa i8i abc 0aa i8i The pattern could be written more simply as [a-z\d] Matching zero or more times with star (*) Text: Anna Jones and a friend owned an anaconda Regex: a\w* Options: IgnoreCase Matches: Anna Jones and a friend owned an anaconda Anna and a an anaconda Matching one or more times with plus (+) Text: Anna Jones and a friend owned an anaconda Regex: a\w+ Options: IgnoreCase Matches: Anna Jones and a friend owned an anaconda Anna and an anaconda Matching zero or one times with question mark (?) Text: Anna Jones and a friend owned an anaconda Regex: an? Options: IgnoreCase Matches: Anna Jones and a friend owned an anaconda An a an a an an a a Specifying the number of matches Text: Anna Jones and Anne owned an anaconda Regex: an{2} Options: IgnoreCase Matches: Anna Jones and Anne owned an anaconda Ann Ann Text: Anna and Anne lunched with an anaconda annnnnex Regex: an{2,3} Options: IgnoreCase Matches: Anna and Anne lunched with an anaconda annnnnex Ann Ann annn The Regex stops matching after the maximum number of matches has been found. Matching the start and end of a string Text: an anaconda ate Anna Jones Regex: ^a Matches: an anaconda ate Anna Jones "a" at position 1 Text: "an anaconda ate Anna Jones" Regex: \w+$ Options: Multiline, IgnoreCase Matches: Jones

评论