using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace _01_字符串提取
{
class Program
{
static void Main(string[] args)
{
//Regex regex = new Regex(@"\d+");
//Match match = regex.Match("age = 30 ");
//if (match.Success)
//{
// Console.WriteLine(match.Value);
//}
//分组匹配
//Match match= Regex.Match("age=30", @"([A-Z]+)=(\d+)", RegexOptions.IgnoreCase);
//if (match.Success)
//{
// //匹配组 0 返回的是整个正则表达式匹配的结果
// //Console.WriteLine(match.Groups[0]);
// Console.WriteLine(match.Groups[1]);
// Console.WriteLine(match.Groups[2]);
//}
//从文件路径中提取出文件名(包含后缀) @"^.+/(.+)$"。比如从c:/a/b.txt中提取出b.txt这个文件名出来。项目中用Path.GetFileName更好。贪婪模式。
//Match match = Regex.Match("c:/a/b.txt", @"^.+/(.+)$");
//if (match.Success)
//{
// Console.WriteLine(match.Groups[1].Value);
//}
//Match match = Regex.Match("June 26, 1951", @"(?<month>[a-zA-Z]+)\s+(?<date>\d{1,2}),\s*(?<year>\d{4})");
//if (match.Success)
//{
// Console.WriteLine(match.Groups["year"].Value);
// Console.WriteLine(match.Groups["month"].Value);
// Console.WriteLine(match.Groups["date"].Value);
//}
//Match match = Regex.Match("abc@163.com",@"^(?<name>\w+)@(?<domain>\w{1,26})\.\w+(\.\w+)?$");
//if (match.Success)
//{
// Console.WriteLine(match.Groups["name"].Value);
// Console.WriteLine(match.Groups["domain"].Value);
//}
// 可以用<> 配置名称 显示的话加()
//192.168.10.5[port=21,type=ftp]
string str= "192.168.10.5[port=21]";
string ip = "";
string port = "";
string type = "http";
string reg = @"(?<ip>[12]?\d?\d\.[12]?\d?\d\.[12]?\d?\d.[12]?\d?\d)\[port=(?<port>\d{1,5})(,type=(?<type>[a-zA-Z]+))?\]";
Match match = Regex.Match(str, reg);
if (match.Success)
{
ip = match.Groups["ip"].Value;
port = match.Groups["port"].Value;
if (!string.IsNullOrEmpty(match.Groups["type"].Value)) // 做一个判断是否为空
{
type = match.Groups["type"].Value;
}
}
Console.WriteLine(ip);
Console.WriteLine(port);
Console.WriteLine(type);
Console.Read();
}
}
}
贪婪模式:
正则表达式 贪婪模式:尽量多的去匹配内容 如果要变就需要改成非贪婪模式
如我是(.+) 贪婪的 我是(.+?) 非贪婪的
不懂的话,我在给你们举一个例子:
我是一个人。它是动物。你是学生 贪婪是直接匹配的最后一个。 非贪婪是匹配的第一个
另外:
我是一个人。它是动物。你是学生 贪婪是直接匹配的最后一个。 我是一个人。它是动物。你是学生 贪婪是直接匹配的最后一个。 如果要获得第二个。就不能用贪婪非贪婪