正则表达式的一些补充
正则中的断言
前面我们定位字符 $前面的字符必须在结尾 ^它后面的字符必须在开头,但如果我们要匹配abcd1234dfdd12313 我想找到d前面的数字怎么办。 断言。分左侧右侧
左侧 (?<=正则) 匹配出左边满足某个正则的子串
我想匹配出d后面的数字 (?<=d)\d+ 1234 12313
string pattern = @"(?<=d)\d+";
string str = "abcd1234dfdd12313";
MatchCollection match = Regex.Matches(str, pattern);
foreach (Match i in match)
{
Console.WriteLine(i);
}
右侧 (?=正则)匹配出子串,并且该字串在字符串的右边必须满足括号中的正则
string pattern2 = @"\d+(?=d)";
MatchCollection match2 = Regex.Matches(str, pattern2);
foreach (Match i in match2)
{
Console.WriteLine(i);
}
要求大家匹配出当前文件夹下面所有txt文件的文件名
string pattern3 = @"(?<=\./).+(?=\.txt$)";
string[] files = Directory.GetFiles("./");
foreach (string file in files)
{
if(Regex.IsMatch(file, pattern3))
{
Console.WriteLine(file);
}
Match match3 = Regex.Match(file, pattern3);
if (match3.Success)
{
Console.WriteLine(match3);
}
}
另外两种方式匹配中间的字符串
string pattern4 = @"\./(.+)\.txt$"; //把想要匹配到的内容用括号括起来
string[] files2 = Directory.GetFiles("./");
foreach (string file in files2)
{
Match match3 = Regex.Match(file, pattern3);
Console.WriteLine(match3.Groups[0]);//如果是下标0表示得到的是匹配到的子串。
Console.WriteLine(match3.Groups[1]);//下标1得到的是第一个括号中匹配到的内容
//如果括号比较多,难以查找
}
我们也可以使用占位符的形式 比如格式化字符串$"{变量名}" "{0}{1}",name,name2
string pattern5 = @"\./(?<name>.+)\.txt$";//(?<占位符>正则) match.Groups["占位符名称"]
while (true)
{
string str1 = Console.ReadLine();
Match match1 = Regex.Match(str1, pattern5);
Console.WriteLine(match1.Groups["name"]);
}
所有类型都可以用object表示
object i = 1;
object a = "";
object b = new int[] { };
object c = new Person();
JSON
string json =File.ReadAllText("./json.txt");
Console.WriteLine(json);
//将json数据进行转化
Human human = JsonMapper.ToObject<Human>(json);
Console.WriteLine(human.person.name);
Person[] person = JsonMapper.ToObject<Person[]>(json);//也可以用数组
foreach (Person ii in person)
{
Console.WriteLine(ii.name);
}
Student student = new Student("小黑", 16);
//怎么将对象转换为json字符串
string json1 = JsonMapper.ToJson(student);
Console.WriteLine(json1);//中文被进行了转码