简体   繁体   English

正则表达式在C#中不匹配

[英]Regex not matching in C#

I have the following string: 我有以下字符串:

 string error = "<MESSAGES><MESSAGE SEVERITY=\"2\" NUMBER=\"16\" TEXT=\"The Record Case is locked by user\" /></MESSAGES>";

I want to match between the TEXT=\\" and the following \\ 我想匹配TEXT=\\"和以下\\

I'm using the following expression var regex = new Regex(@"TEXT=\\\\""(.*?)\\\\"); 我正在使用以下表达式var regex = new Regex(@"TEXT=\\\\""(.*?)\\\\");

Expresso tells me this regex is correct. Expresso告诉我这个正则表达式是正确的。 RegExr tells me this regex is correct. RegExr告诉我这个正则表达式是正确的。

But C# disagrees. 但C#不同意。

I've tried 我试过了

  • Groups[] and match.Value. Groups[]和match.Value。
  • \\x22 instead of " as I thought it might be an escape problem. \\x22而不是"因为我认为它可能是一个逃避问题。
  • /TEXT=\\""(.*?)\\/g

All, to no avail. 一切都无济于事。

What am I missing? 我错过了什么?

Use XElement , you have an XML fragment: 使用XElement ,您有一个XML片段:

var error = "<MESSAGES><MESSAGE SEVERITY=\"2\" NUMBER=\"16\" TEXT=\"The Record Case is locked by user\" /></MESSAGES>";
var xe = XElement.Parse(error);
var res = xe.Elements("MESSAGE")
                   .Where(p => p.HasAttributes && p.Attributes("TEXT") != null)
                   .Select(n => n.Attribute("TEXT").Value)
                   .ToList();

Output: 输出:

在此输入图像描述

Mind that with very large input strings, .*? 请注意,输入字符串非常大, .*? may cause catastrophic backtracking, that is why you should avoid using it whenever possible. 可能导致灾难性的回溯,这就是为什么你应该尽可能避免使用它。 If you need a regex for this (because some of your input is not XML-valid), you can use: 如果你需要一个正则表达式(因为你的一些输入不是XML有效的),你可以使用:

var attr_vals = Regex.Matches(error, @"(?i)\bTEXT=""([^""]+)""")
             .OfType<Match>()
             .Select(p => p.Groups[1].Value)
             .ToList();

(2 times faster than Karthik's, tested on regexhero.com) (比Karthik快2倍,在regexhero.com上测试过)

Output: 输出:

在此输入图像描述

Mind that with regex, you will get all XML entities untouched (eg &amp; and not & ). 请注意,使用正则表达式,您将获得所有未更改的XML实体(例如&amp;而不是& )。 You will have to use System.Web.HttpUtility later. 稍后您将不得不使用System.Web.HttpUtility

使用以下内容(您的实际字符串将被编译为不带\\的字符串..因为您只是将它们用作转义字符):

var regex = new Regex(@"TEXT=""([^""]+)""");

This works for me: 这对我有用:

Regex.Match(error, "TEXT=\\\"(.*?)\\\"")

You need to escape both \\ and " character with \\ 你需要的逃生\\"字与\\

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM