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?
source to share
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:
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:
Remember that with regex you will get all XML objects unmodified (like, &
not &
). You will have to use it System.Web.HttpUtility
later.
source to share