2

I have a portion of XAML string in code-behind like this

string str = "<Button Name = \"btn1\" Foo = \"Bar"\ /><TextBox Name=\"txtbox1\">"

What should be the regex to find value of only Name attributes.

I want

btn1
txtbox1

How?

Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208
  • 2
    http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags – Lakis May 30 '12 at 12:43
  • See http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags – woz May 30 '12 at 12:43
  • Why don't you use an xml/html parser? – L.B May 30 '12 at 12:45
  • 1
    I am sure this is a duplicate of a duplicate. This is one: http://stackoverflow.com/questions/317053/regular-expression-for-extracting-tag-attributes – woz May 30 '12 at 12:46
  • Here is another: http://stackoverflow.com/questions/6481320/how-to-remove-single-attribute-with-quotes-via-regex – woz May 30 '12 at 12:47

3 Answers3

1

And you definitely don't want to do this?

string str = "<Button Name = \"btn1\" /><TextBox Name=\"txtbox1\"/>";
var attrs = XElement.Parse("<r>"+str+"</r>").Elements().Attributes("Name").Select(a => a.Value);

foreach (var attr in attrs) Console.WriteLine(attr);
yamen
  • 15,390
  • 3
  • 42
  • 52
  • I am taking XElement from System.Xml.Linq. If that is correct then Elements().Attributes() says its an error. – Nikhil Agrawal May 30 '12 at 13:01
  • You need to add a `using System.Xml.Linq` block in your code, rather than directly access `System.Xml.Linq.XElement`, since `Attributes()` is an extension method on `IEnumerable` that needs to be brought into scope. Also note I'm using `.Attributes("Name")` now after re-reading your question. – yamen May 30 '12 at 13:12
1

Instead of LINQ, you can also use XPath to get the value. This will get you the name of the first Button:

string str = "<Button Name = \"btn1\" /><TextBox Name=\"txtbox1\"/>";
XmlDocument doc = new XmlDocument();
doc.LoadXml("<root>" + str + "</root>");
string name = doc.SelectSingleNode("root/Button/@Name").InnerText;

Or, if you just want to get the first name attribute for any item:

string name = doc.SelectSingleNode("root/*/@Name").InnerText;

Or to get a list of all the name attributes for all items:

foreach (XmlNode node in doc.SelectNodes("root/*/@Name"))
{
    string name = node.InnerText';
}

etc.

Steven Doggart
  • 43,358
  • 8
  • 68
  • 105
0

Try this if you can use lookaround:

(?<=\bName\b\s*=\s*")[^"]+
Tiksi
  • 471
  • 1
  • 6
  • 15