正则表达式-定位点
匹配開頭的結尾的,主要差別在使用了RegexOptions.Multiline多行模式上,看下面兩個示例:
?
再看MSDN的敘述:
^?
指定匹配必須出現在字符串的開頭或行的開頭。有關更多信息,請參閱正則表達式選項中的?Multiline?選項。?
$?
指定匹配必須出現在以下位置:字符串結尾、字符串結尾的?\n?之前或行的結尾。有關更多信息,請參閱正則表達式選項中的?Multiline?選項。?
\A?
指定匹配必須出現在字符串的開頭(忽略?Multiline?選項)。?
\Z?
指定匹配必須出現在字符串的結尾或字符串結尾的?\n?之前(忽略?Multiline?選項)。?
\z?
指定匹配必須出現在字符串的結尾(忽略?Multiline?選項)。
?
?
連續匹配:\G\G?定位標記指定匹配必須出現在上一個匹配結束的地方。?通過?Regex.Matches?或?Match.NextMatch?方法使用此定位點時,它確保所有匹配項是連續的。
下面的示例使用正則表達式從以逗號分隔的字符串提取嚙齒類的名稱。
using System; using System.Text.RegularExpressions;public class Example {public static void Main(){string input = "capybara,squirrel,chipmunk,porcupine,gopher," + "beaver,groundhog,hamster,guinea pig,gerbil," + "chinchilla,prairie dog,mouse,rat";string pattern = @"\G(\w+\s?\w*),?";Match match = Regex.Match(input, pattern);while (match.Success) {Console.WriteLine(match.Groups[1].Value);match = match.NextMatch();} } } // The example displays the following output: // capybara // squirrel // chipmunk // porcupine // gopher // beaver // groundhog // hamster // guinea pig // gerbil // chinchilla // prairie dog // mouse // rat?
?
單詞邊界:\b\b?定位標記指定匹配必須出現在單詞字符(\w?語言元素)和非單詞字符(\W?語言元素)之間的邊界上。?單詞字符包含字母數字字符和下劃線;非單詞字符是非字母數字或下劃線的任何字符。(有關更多信息,請參見正則表達式中的字符類。)匹配也可能出現在字符串的開頭或結尾的單詞邊界。
\b?定位標記經常用于確保子表達式匹配整個單詞而不只是匹配單詞的開頭或結尾。?下例中的正則表達式?\bare\w*\b?演示此用法。?它匹配以子字符串“are”開頭的任意單詞。?示例的輸出還演示?\b?同時匹配輸入字符串的開頭和結尾。
using System; using System.Text.RegularExpressions;public class Example {public static void Main(){string input = "area bare arena mare";string pattern = @"\bare\w*\b";Console.WriteLine("Words that begin with 'are':");foreach (Match match in Regex.Matches(input, pattern))Console.WriteLine("'{0}' found at position {1}",match.Value, match.Index);} } // The example displays the following output: // Words that begin with 'are': // 'area' found at position 0 // 'arena' found at position 10?
?
非字邊界:\B\B?定位標記指定匹配不得出現在單詞邊界。?它是與?\b?定位點相反的定位點。
下面的示例使用?\B?定位點找到單詞中子字符串“qu”的匹配項。?正則表達式模式?\Bqu\w+?匹配以“qu”開頭的子字符串,該字符串不會開始單詞并延續到字符串的結尾。
using System; using System.Text.RegularExpressions;public class Example {public static void Main(){string input = "equity queen equip acquaint quiet";string pattern = @"\Bqu\w+";foreach (Match match in Regex.Matches(input, pattern))Console.WriteLine("'{0}' found at position {1}", match.Value, match.Index);} } // The example displays the following output: // 'quity' found at position 1 // 'quip' found at position 14 // 'quaint' found at position 21?
?
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
- 上一篇: 数据类型和Json格式
- 下一篇: WordPress 5.1:从CSRF到