正则表达式的先行断言(lookahead)和后行断言(lookbehind)
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace ConsoleApp1 { class Program { static void Main(string[] args) {//正则表达式的先行断言(lookahead)和后行断言(lookbehind) //参考https://www.cnblogs.com/chip/p/4278135.html //我这里将字符串左边作为前,右边作为后,与英语是相反的。 string ss = "Ab110cd120"; Console.WriteLine("字符串:" + ss); string p2 = "[A-Za-z]+(?=110)"; //(?=pattern) 正向先行断言 :找后面跟着数字110的字母,答案是Ab Match m2 = Regex.Match(ss, p2); Console.WriteLine("后面有数字110的字符是:"+m2.Value); string p3= "[A-Za-z]+(?!110)"; //(?!pattern) 负向先行断言 :找后面跟着的不是110的字母,答案是A Match m3 = Regex.Match(ss, p3); Console.WriteLine("后面不是110的字符是:" + m3.Value); string p4 = "(?<=110)[A-Za-z]+"; //(?<=pattern) 正向后行断言 :找前面是110的字母,答案是cd Match m4 = Regex.Match(ss, p4); Console.WriteLine("前面是110的字符是:" + m4.Value); string p5 = "(?<!Ab)[0-9]+"; //(?<!pattern) 负向后行断言 :找前面不是Ab的数字,答案是10 Match m5 = Regex.Match(ss, p5); Console.WriteLine("前面不是Ab的数字是:" + m5.Value); Console.Read(); } } }