C#正则示例

//====Regex.Match只能提取第一个匹配字符串
static void Main()
{
string str = "zh12jie56中国";
Match match = Regex.Match(str, "\d+");
Console.WriteLine(match.Value);//
Console.ReadKey();
}
//===Regex.Matches提取字符串中所有匹配正则的字符串====
static void Main()
{
string str = "zh12jie56中国";
MatchCollection matches = Regex.Matches(str, "\d+");
foreach (Match item in matches)
{
Console.WriteLine(item.Value);
}
Console.ReadKey();
}
static void Main()
{
string str = "你aaa好aa哈哈a你";
str = Regex.Replace(str, "a+", "A");//把a替换成A
Console.WriteLine(str);
Console.ReadKey();
}
/引用替换1。将hello ‘welcome’ to ‘China’ 替换成 hello 【welcome】 to 【China】
如果匹配的正则字符串中有分组,即有(),可以在替换字符串中用$number来进行引用替换。
从左往右,第1对()里的内容用$1引用,第2对()里的内容用$2引用,
依次类推。$0表示正则匹配到的完整字符串。
/
static void Main()
{
string str = "hello 'welcome' to 'China'";
str = Regex.Replace(str, "'(.+?)'", "【$1】");
Console.WriteLine(str);
Console.ReadKey();
}

//引用替换2。隐藏手机号码中间4位数
static void Main()
{
string msg = "朱杰13576071646张三15878987656李四13876788990高艳红15087655678";
msg = Regex.Replace(msg, @"([0-9]{3})[0-9]{4}([0-9]{4})", "$1****$2");
Console.WriteLine(msg);
Console.ReadKey();
}
//判断u在字符串zhujie中是否存在
static void Main(string[] args)
{
string str = "zhujie";
bool b=Regex.IsMatch(str, "u") ;//结果true为存在,false为不存在
Console.WriteLine(b);
Console.ReadKey();
}
//计算/在字符串"zhu/jie/123zj/pwj"中出现的次数
static void Main(string[] args)
{
string str = "zhu/jie/123zj/pwj";
int i = Regex.Matches(str, @"/").Count;//
Console.WriteLine(i);
Console.ReadKey();
}
/引用替换1。将hello ‘welcome’ to ‘China’ 替换成 hello 【welcome】 to 【China】
如果匹配的正则字符串中有分组,即有(),可以在替换字符串中用$number来进行引用替换。
从左往右,第1对()里的内容用$1引用,第2对()里的内容用$2引用,
依次类推。$0表示正则匹配到的完整字符串。
/
static void Main()
{
string str = "hello 'welcome' to 'China'";
str = Regex.Replace(str, "'(.+?)'", "【$1】");
Console.WriteLine(str);
Console.ReadKey();
}

//引用替换2。隐藏手机号码中间4位数
static void Main()
{
string msg = "朱杰13576071646张三15878987656李四13876788990高艳红15087655678";
msg = Regex.Replace(msg, @"([0-9]{3})[0-9]{4}([0-9]{4})", "$1****$2");
Console.WriteLine(msg);
Console.ReadKey();
}
//判断u在字符串zhujie中是否存在
static void Main(string[] args)
{
string str = "zhujie";
bool b=Regex.IsMatch(str, "u") ;//结果true为存在,false为不存在
Console.WriteLine(b);
Console.ReadKey();
}

猜你喜欢

转载自www.cnblogs.com/zhujie-com/p/12094688.html
今日推荐