C#中的正则表达式和示例
正则表达式是可以与输入文本匹配的模式。.Net框架提供了允许此类匹配的正则表达式引擎。
让我们看看如何分割正则表达式。
要使用正则表达式拆分字符串,请使用Regex.split。
假设我们的字符串是-
string str = "Hello\r\nWorld";
现在使用Regex.split分割字符串,如下所示-
string[] res = Regex.Split(str, "\r\n");
以下是在C#中使用正则表达式拆分字符串的完整代码-
示例
using System;
using System.Text.RegularExpressions;
class Demo {
static void Main() {
string str = "Hello\r\nWorld";
string[] res = Regex.Split(str, "\r\n");
foreach (string word in res) {
Console.WriteLine(word);
}
}
}现在让我们看一个删除多余空格的示例。
示例
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();
}
}
}热门推荐
10 小红书平安祝福语简短
11 生日祝福语大全女孩简短
12 收生日红包祝福语 简短
13 领证幽默祝福语简短
14 法考面试祝福语简短
15 老哥出门祝福语简短语
16 送灯祝福语简短独特
17 幼儿狗年祝福语大全简短
18 好听的元旦简短祝福语