您的位置:首页 > 其它

解析几个正则表达式

2014-06-24 12:56 204 查看
本文摘自:http://www.cnblogs.com/xiexingen/archive/2013/01/07/2850172.html

NET Framework 中的正则表达式引擎由 Regex 类表示。 正则表达式引擎负责分析和编译正则表达式,并执行用于将正则表达式模式与输入字符串相匹配的操作。

可以调用 Regex 类的方法来执行下列操作:

确定字符串是否与正则表达式模式匹配。

提取单个匹配项或第一个匹配项。

提取所有匹配项。

替换匹配的子字符串。

将单个字符串拆分成一个字符串数组。

以下各部分对这些操作进行了描述。

匹配正则表达式模式

如果字符串与模式匹配,则 Regex.IsMatch 方法返回 true;如果字符串与模式不匹配,则此方法返回 false。IsMatch 方法通常用于验证字符串输入。 例如,下面的代码将确保字符串与有效的美国社会保障号匹配。

using System;
using System.Text.RegularExpressions;

public class Example
{
public static void Main()
{
string[] values = { "111-22-3333", "111-2-3333"};
string pattern = @"^\d{3}-\d{2}-\d{4}$";
foreach (string value in values) {
if (Regex.IsMatch(value, pattern))
Console.WriteLine("{0} is a valid SSN.", value);
else
Console.WriteLine("{0}: Invalid", value);
}
}
}
// The example displays the following output:
//       111-22-3333 is a valid SSN.
//       111-2-3333: Invalid


正则表达式模式 ^\d{3}-\d{2}-\d{4}$ 的含义如下表所示。

模式说明
^匹配输入字符串的开头部分。
\d{3}匹配三个十进制数字。
-匹配连字符。
$匹配输入字符串的末尾部分。

提取单个匹配项或第一个匹配项

Regex.Match 方法返回一个 Match 对象,该对象包含有关与正则表达式模式匹配的第一个子字符串的信息。 如果 Match.Success 属性返回 true,则表示已找到一个匹配项,可以通过调用 Match.NextMatch 方法来检索有关后续匹配项的信息。 这些方法调用可以继续进行,直到 Match.Success 属性返回 false。 例如,下面的代码使用 Regex.Match(String, String) 方法查找重复的单词在字符串中的第一个匹配项。 然后,此代码调用Match.NextMatch 方法查找任何其他匹配项。 该示例将在每次调用方法后检查 Match.Success 属性以确定当前匹配是否成功,并确定是否应接着调用 Match.NextMatch 方法。

using System;
using System.Text.RegularExpressions;

public class Example
{
public static void Main()
{
string input = "This is a a farm that that raises dairy cattle.";
string pattern = @"\b(\w+)\W+(\1)\b";
Match match = Regex.Match(input, pattern);
while (match.Success)
{
Console.WriteLine("Duplicate '{0}' found at position {1}.",
match.Groups[1].Value, match.Groups[2].Index);
match = match.NextMatch();
}
}
}
// The example displays the following output:
//       Duplicate 'a' found at position 10.
//       Duplicate 'that' found at position 22.


正则表达式模式 \b(\w+)\W+(\1)\b 的含义如下表所示

模式说明
\b从单词边界开始进行匹配。
(\w+)匹配一个或多个单词字符。 这是第一个捕获组。
\W+匹配一个或多个非单词字符。
(\1)匹配第一个捕获的字符串。 这是第二个捕获组。

\b在单词边界处结束匹配。

替换匹配的子字符串

Regex.Replace 方法会将与正则表达式模式匹配的每个子字符串替换为指定的字符串或正则表达式模式,并返回进行了替换的整个输入字符串。 例如,下面的代码会在字符串 中的十进制数字前添加美国货币符号。

using System;
using System.Text.RegularExpressions;

public class Example
{
public static void Main()
{
string pattern = @"\b\d+\.\d{2}\b";
string replacement = "$$$&";
string input = "Total Cost: 103.64";
Console.WriteLine(Regex.Replace(input, pattern, replacement));
}
}
// The example displays the following output:
//       Total Cost: $103.64


正则表达式模式 \b\d+\. \d{2}\b is interpreted as shown in the following table.

模式说明
\b在单词边界处开始匹配。
\d+匹配一个或多个十进制数字。
\.匹配句点。
\d{2}匹配两个十进制数字。

\b在单词边界处结束匹配。

替换模式 $$$& 的含义如下表所示。

模式说明
$$美元符号 ($) 字符。
$&整个匹配的子字符串。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: