正则表达式是匹配输入文本的模式。.net框架提供了允许这种匹配的正则表达式引擎。模式由一个或多个字符文字,运算符或构造组成。
有各种类型的字符,运算符和结构,可以让您用来定义正则表达式。点击以下链接查找这些结构。
正则表达式 - regex
类用于表示正则表达式。 它有以下常用的方法:
序号 | 方法 | 描述 |
---|---|---|
1 | public bool ismatch(string input) | 指示在正则表达式构造函数中指定的正则表达式是否在指定的输入字符串中找到匹配项。 |
2 | public bool ismatch(string input, int startat) | 指示在正则表达式构造函数中指定的正则表达式是否在指定的输入字符串(input )中找到匹配,从字符串中指定的起始(startat )位置开始。 |
3 | public static bool ismatch(string input, string pattern) | 在指定的正则表达式是否在指定的输入字符串中找到匹配项。 |
4 | public matchcollection matches(string input) | 搜索所有出现正则表达式的指定输入字符串。 |
5 | public string replace(string input, string replacement) | 在指定的输入字符串中,将与正则表达式模式匹配的所有字符串替换为指定的替换字符串(replacementreplacement )。 |
6 | public string[] split(string input) | 将输入字符串拆分为由正则表达式构造函数中指定的正则表达式模式定义的位置的子字符串数组。 |
有关方法和属性的完整列表,请阅读microsoft c# 文档。
以下示例匹配以“s”
开头的单词:
using system;
using system.text.regularexpressions;
namespace regexapplication
{
class program
{
private static void showmatch(string text, string expr)
{
console.writeline("the expression: " + expr);
matchcollection mc = regex.matches(text, expr);
foreach (match m in mc)
{
console.writeline(m);
}
}
static void main(string[] args)
{
string str = "a thousand splendid suns";
console.writeline("matching words that start with 's': ");
showmatch(str, @"\bs\s*");
console.readkey();
}
}
}
当编译和执行上述代码时,会产生以下结果:
matching words that start with 's':
the expression: \bs\s*
splendid
suns
以下示例匹配以'm'
开头并以'e'
结尾的单词:
using system;
using system.text.regularexpressions;
namespace regexapplication
{
class program
{
private static void showmatch(string text, string expr)
{
console.writeline("the expression: " + expr);
matchcollection mc = regex.matches(text, expr);
foreach (match m in mc)
{
console.writeline(m);
}
}
static void main(string[] args)
{
string str = "make maze and manage to measure it";
console.writeline("matching words start with 'm' and ends with 'e':");
showmatch(str, @"\bm\s*e\b");
console.readkey();
}
}
}
当编译和执行上述代码时,会产生以下结果:
matching words start with 'm' and ends with 'e':
the expression: \bm\s*e\b
make
maze
manage
measure
此示例替换了额外多余的空格:
using system;
using system.text.regularexpressions;
namespace regexapplication
{
class program
{
static void main(string[] args)
{
string input = "hello world ";
string pattern = "\\s+";
string replacement = " ";
regex rgx = new regex(pattern);
string result = rgx.replace(input, replacement);
console.writeline("original string: {0}", input);
console.writeline("replacement string: {0}", result);
console.readkey();
}
}
}
当编译和执行上述代码时,会产生以下结果:
original string: hello world
replacement string: hello world