Regex does not match in C #

I have the following line:

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

      

I want to combine between TEXT=\"

and the following\

I am using the following expression var regex = new Regex(@"TEXT=\\""(.*?)\\");

Expresso tells me that this regex is correct. RegExr tells me that this regex is correct.

But C # disagrees.

I tried

  • Groups[]

    and match.Value.
  • \x22

    instead "

    , as I thought it might be an escape issue.
  • /TEXT=\""(.*?)\/g

All to no avail.

What am I missing?

+3


source to share


3 answers


Use XElement

, you have an XML snippet:

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:

enter image description here

Remember that it .*?

can result in a catastrophic return on very large input strings , so you should avoid using it whenever possible. If you need a regex for this (because some of your inputs are not valid XML), you can use:



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

      

(2x faster than Karthik's tested on regexhero.com)

Output:

enter image description here

Remember that with regex you will get all XML objects unmodified (like, &amp;

not &

). You will have to use it System.Web.HttpUtility

later.

+8


source


Use the following (your actual string will be compiled into a string without \

.. since you are just using them as escape characters):



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

      

+2


source


This works for me:

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

      

You need to escape the character \

and "

with\

+1


source







All Articles