正则表达式在线匹配,但不在C#代码中(Regex matches online but not in C# code)
这个正则表达式适用于在线正则表达式测试人员,但是当我尝试这段代码时,正则表达式不匹配。
Regex regex = new Regex(@"^\.lnr-(.*)\:before \{$", RegexOptions.Compiled | RegexOptions.Multiline); string css = System.IO.File.ReadAllText(Server.MapPath("/linearicons-free.css")); foreach (Match match in regex.Matches(css)) { //doing sth }我错过了什么?
This regex works at online regex testers but when I try this piece of code regex does not match.
Regex regex = new Regex(@"^\.lnr-(.*)\:before \{$", RegexOptions.Compiled | RegexOptions.Multiline); string css = System.IO.File.ReadAllText(Server.MapPath("/linearicons-free.css")); foreach (Match match in regex.Matches(css)) { //doing sth }What am I missing ?
最满意答案
当C#解析字符串时,最后会有一个\n 。 所以你的模式^\.lnr-(.*):before \{$失败^\.lnr-(.*):before \{$因为你期望的最后一个charcater是{
将模式更改为^\.lnr-(.*):before \{\s$ ,它应该可以工作。
你可以在这里测试.NET正则表达式而不是regex101.com
There is a \n at the end when C# is parsing the string. So your pattern^\.lnr-(.*):before \{$ fails because the last charcater you are expecting is {
Change the pattern to ^\.lnr-(.*):before \{\s$ and it should work.
you can test the .NET regexes here instead of regex101.com
更多推荐
发布评论