Practical regular expression matching and replacement

Regular expressions are very useful to find, match, process strings, replace and transform strings, input and output, etc. And various languages ​​are supported, such as .NET regular library, JDK regular package, Perl, JavaScript and other scripting languages ​​support regular expressions. Here are some commonly used regular expressions.

character

describe

\ Marks the next character as a special character, or a literal character, or a backreference, or an octal escape. For example, 'n' matches the character "n". '\n' matches a newline. The sequence '\\' matches "\" and "\(" matches "(".
^ Matches the starting position of the input string. If the Multiline property of the RegExp object is set, ^ also matches the position after '\n' or '\r'.
$ Matches the end of the input string. If the Multiline property of the RegExp object is set, $ also matches the position before '\n' or '\r'.
* Matches the preceding subexpression zero or more times. For example, zo* matches "z" as well as "zoo". * is equivalent to {0,}.
+ Matches the preceding subexpression one or more times. For example, 'zo+' matches "zo" and "zoo", but not "z". + is equivalent to {1,}.
? Matches the preceding subexpression zero or one time. For example, "do(es)?" matches "do" or "do" in "does". ? Equivalent to {0,1}.
{n} n  is a non-negative integer. Match a certain number of  n  times. For example, 'o{2}' would not match the 'o' in "Bob", but would match the two o's in "food".
{n,} n  is a non-negative integer. Match at least n  times. For example, 'o{2,}' would not match the 'o' in "Bob", but would match all o's in "foooood". 'o{1,}' is equivalent to 'o+'. 'o{0,}' is equivalent to 'o*'.
{n,m} Both m  and  n  are non-negative integers, where n  <=  m . Match at least  n  times and at most  m  times. For example, "o{1,3}" will match the first three o's in "fooooood". 'o{0,1}' is equivalent to 'o?'. Note that there can be no spaces between the comma and the two numbers.
? When the character immediately follows any one of the other qualifiers (*, +, ?, { n }, { n ,}, { n , m }), the matching pattern is non-greedy. The non-greedy mode matches as little of the searched string as possible, while the default greedy mode matches as much of the searched string as possible. For example, for the string "oooo", 'o+?' would match a single "o", and 'o+' would match all 'o's.
. Matches any single character except "\n". To match any character including '\n', use a pattern like '[.\n]'.
(pattern) Match  pattern  and get that match. The retrieved matches can be obtained from the resulting Matches collection, using the  SubMatches collection in VBScript and the $0$9  properties  in JScript  . To match parentheses characters, use '\(' or '\)'.
(?:pattern) Matches  the pattern  but does not get the result of the match, that is, it is a non-getting match and is not stored for later use. This is useful when using the "or" character (|) to combine parts of a pattern. For example, 'industr(?:y|ies) is a shorter expression than 'industry|industries'.
(?=pattern) Forward lookahead,   matches the lookup string at the beginning of any string matching pattern . This is a non-acquisition match, that is, the match does not need to be acquired for later use. For example, 'Windows (?=95|98|NT|2000)' matches "Windows" in "Windows 2000", but not "Windows" in "Windows 3.1". Lookahead consumes no characters, that is, after a match occurs, the search for the next match begins immediately after the last match, not after the character containing the lookahead.
(?!pattern) Negative lookahead,   which matches the lookup string at the beginning of any string that does not match pattern . This is a non-acquisition match, that is, the match does not need to be acquired for later use. For example 'Windows (?!95|98|NT|2000)' matches "Windows" in "Windows 3.1", but not "Windows" in "Windows 2000". Lookahead consumes no characters, that is, after a match occurs, the search for the next match begins immediately after the last match, not after the character containing the lookahead
x | and matches  x  or  y . For example, 'z|food' matches "z" or "food". '(z|f)ood' matches "zood" or "food".
[xyz] character collection. Matches any one of the included characters. For example, '[abc]' can match 'a' in "plain".
[^xyz] A collection of negative characters. Matches any character not included. For example, '[^abc]' matches the 'p' in "plain".
[a-z] 字符范围。匹配指定范围内的任意字符。例如,'[a-z]' 可以匹配 'a' 到 'z' 范围内的任意小写字母字符。
[^a-z] 负值字符范围。匹配任何不在指定范围内的任意字符。例如,'[^a-z]' 可以匹配任何不在 'a' 到 'z' 范围内的任意字符。
\b 匹配一个单词边界,也就是指单词和空格间的位置。例如, 'er\b' 可以匹配"never" 中的 'er',但不能匹配 "verb" 中的 'er'。
\B 匹配非单词边界。'er\B' 能匹配 "verb" 中的 'er',但不能匹配 "never" 中的 'er'。
\cx 匹配由 指明的控制字符。例如, \cM 匹配一个 Control-M 或回车符。x 的值必须为 A-Z 或 a-z 之一。否则,将 c 视为一个原义的 'c' 字符。
\d 匹配一个数字字符。等价于 [0-9]。
\D 匹配一个非数字字符。等价于 [^0-9]。
\f 匹配一个换页符。等价于 \x0c 和 \cL。
\n 匹配一个换行符。等价于 \x0a 和 \cJ。
\r 匹配一个回车符。等价于 \x0d 和 \cM。
\s 匹配任何空白字符,包括空格、制表符、换页符等等。等价于 [ \f\n\r\t\v]。
\S

匹配任何非空白字符。等价于 [^ \f\n\r\t\v]。

\t 匹配一个制表符。等价于 \x09 和 \cI。
\v 匹配一个垂直制表符。等价于 \x0b 和 \cK。
\w 匹配包括下划线的任何单词字符。等价于'[A-Za-z0-9_]'。
\W 匹配任何非单词字符。等价于 '[^A-Za-z0-9_]'。
\xn 匹配 n,其中 n 为十六进制转义值。十六进制转义值必须为确定的两个数字长。例如,'\x41' 匹配 "A"。'\x041' 则等价于 '\x04' & "1"。正则表达式中可以使用 ASCII 编码。
\num 匹配 num,其中 num 是一个正整数。对所获取的匹配的引用。例如,'(.)\1' 匹配两个连续的相同字符。
\n 标识一个八进制转义值或一个向后引用。如果 \n 之前至少 n个获取的子表达式,则 n 为向后引用。否则,如果 n 为八进制数字 (0-7),则 n 为一个八进制转义值。
\nm 标识一个八进制转义值或一个向后引用。如果 \nm 之前至少有 nm 个获得子表达式,则 nm 为向后引用。如果 \nm 之前至少有 n 个获取,则 n 为一个后跟文字 的向后引用。如果前面的条件都不满足,若 n 和 m 均为八进制数字 (0-7),则 \nm 将匹配八进制转义值 nm
\nml 如果 n 为八进制数字 (0-3),且 m 和 l 均为八进制数字 (0-7),则匹配八进制转义值 nml。
/i 使正则表达式对大小写不敏感, (?-i)是关闭大小写不敏感
(?i)te(?-i)st应该匹配TEst,但是不能匹配teST或TEST.
/s 开启“单行模式”,即点号“.”匹配新行符
/m 开启“多行模式”,即“^”和“$”匹配新行符的前面和后面的位置。
^[0-9]*$ 只能输入数字
^\d{n}$ 只能输入n位的数字
^\d{n,}$ 只能输入至少n位的数字
^\d{m,n}$ 只能输入m~n位的数字
^(0|[1-9][0-9]*)$ 只能输入零和非零开头的数字
^[0-9]+(.[0-9]{2})?$ 只能输入有两位小数的正实数
^[0-9]+(.[0-9]{1,3})?$ 只能输入有1~3位小数的正实数
^\+?[1-9][0-9]*$ 只能输入非零的正整数
^\-[1-9][]0-9"*$ 只能输入非零的负整数
^.{3}$ 只能输入长度为3的字符
^[A-Za-z]+$ 只能输入由26个英文字母组成的字符串
^[A-Za-z0-9]+$ 只能输入由数字和26个英文字母组成的字符串
^\w+$ 只能输入由数字、26个英文字母或者下划线组成的字符串
^[a-zA-Z]\w{5,17}$ 验证用户密码:以字母开头,长度在6~18之间,只能包含字符、数字和下划线。
[^%&',;=?$\x22]+ 验证是否含有^%&',;=?$\"等字符
^[\u4e00-\u9fa5]{0,}$ 只能输入汉字
^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$ 验证Email地址
^http://([\w-]+\.)+[\w-]+(/[\w-./?%&=]*)?$ 验证InternetURL
^\d{15}|\d{18}$ 验证身份证号(15位或18位数字)
^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$ 验证IP地址
(\w)\1 匹配两个两个重叠出现的字符

例如,"aabbc11asd", 返回结果为aa bb 11三组match

<(?<tag>[^\s>]+)[^>]*>.*</\k<tag>> 匹配成对的HTML标签
(?!) 不出现,负声明
下例演示如何取得一个<a>标签对中的全部内容,即使其中包含别的HTML tag。 

string newsContent = @"url:<a href=""1.html""><img src=""1.gif"">test<span style=""color:red;"">
 
Regex</span></a>."; 
Regex regEnd = new Regex(@"<\s*a[^>]*>([^<]|<(?!/a))*<\s*/a\s*>",RegexOptions.Multiline); 

 

1. 匹配组

常用的组匹配:(实用)

(exp)

匹配exp并且捕获到一个自动命名的组

(?<name>exp)

匹配exp并且捕获到组’name’
(?=exp) exp出现在声明右侧,但exp不作为匹配

括号中的模式必须出现在声明右侧,但不作为匹配的一部分 ,例如:

输入: public keywod string "abc"; 
正则:\b\w+(?=ing\b),返回“str”,
意思为:匹配以ing结束的单词,但ing不作为返回
(?<=exp) exp出现在声明左侧,但exp不作为匹配

括号中的模式必须出现在声明左侧,但不作为匹配的一部分 ,例如:

输入: public remember string "abc"; 
正则:(?<=\bre)\w+\b,返回“member”,
意思为:匹配以re开头的单词,但re不作为返回

(?!exp)

 

exp不出现在声明右侧,但exp不作为匹配

括号中的模式必须不出现在声明右侧 ,例如:

输入: remember aqa bqu "abc"; 
正则:\b\w*q(?!u)\w*\b,返回“aqa”,
意思为:匹配带q后面不是跟随u的单词

(?<!exp)

exp不出现在声明左侧,但exp不作为匹配

 

输入:public string keywod = "abc"; string value = "test";

目的:匹配 关键字="",例如获得关键字keyword,value;获得等于的值abc和test

表达式:string (?<x>[^=]*?) *= *(?<y>[^;]*?);

代码

private void ParseKeywords(string input)
{
 System.Text.RegularExpressions.MatchCollection mc = 
 System.Text.RegularExpressions.Regex.Matches(input, @"string (?<x>[^=]*?) *= *(?<y>[^;]*?);");
 
 if (mc != null && mc.Count > 0)
 {
 foreach (System.Text.RegularExpressions.Match m in mc)
 {
 string keyword = m.Groups["x"].Value;
 string value = m.Groups["y"].Value;
 }
 }
}

截图

1 

2. 匹配并替换

输入:public <%=classname%>Extension : IExt

目的:匹配 <%= %>中间的classname并替换

表达式:<%=.*%>

代码

private string Replace(string input)
{
 return Regex.Replace(input, @"<%=.*%>", new MatchEvaluator(RefineCodeTag), RegexOptions.Singleline);
}
 
string RefineCodeTag(Match m)
{
 string x = m.ToString();
 
 x = Regex.Replace(x, "<%=", "");
 x = Regex.Replace(x, "%>", "");
 
 return x.Trim() + ",";
}

截图:

2 

正则表达式选项RegexOptions:

ExplicitCapture

n

只有定义了命名或编号的组才捕获

IgnoreCase i 不区分大小写
IgnorePatternWhitespace x 消除模式中的非转义空白并启用由 # 标记的注释。
MultiLine m

多行模式,其原理是修改了^和$的含义

SingleLine s

单行模式,和MultiLine相对应

正则表达式替换的其他功能:

$number 把匹配的第number组替换成替换表达式

这段代码返回的是 “01 012 03 05”

就是说,对组一的每个匹配结果都用"0$1"这个表达式来替换,"0$1"中"$1"由组1匹配的结果代入


public static void Main()
{ 
 string s = "1 12 3 5";
 s = Regex.Replace(s,@"(\d+)(?#这个是注释)","0$1",RegexOptions.Compiled|RegexOptions.IgnoreCase);
 Console.WriteLine(s);
 Console.ReadLine();
 }

${name}

把匹配的组名为"name"的组替换成表达式,

上例的Regex expression改成@"(?<name>\d+)(?#这个是注释)"后面的替换式改为"0${name}"结果是一样的

$$

做$的转义符,如上例表达式改成@"(?<name>\d+)(?#这个是注释)"和"$$${name}",则结果为"$1 $12 $3 $5"

$& 替换整个匹配
$` 替换匹配前的字符
$' 替换匹配后的字符
$+ 替换最后匹配的组
$_ 替换整个字符串

 

3. 匹配URL中文件名

输入http://www.9499.net/page1.htm

目的:从URL地址中提取文件名

表达式:s=s.replace(/(.*\/){0,}([^\.]+).*/ig,"$2") ;

代码

string s = "http://www.9499.net/page1.htm";
s = s.replace(/(.*\/){0,}([^\.]+).*/ig, "$2") ; 

截图:

3

或许您对以下相关文章有兴趣:

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324984536&siteId=291194637