0
votes

I am trying to get all strings enclosed in <*> by using following Regex:

Regex regex = new Regex(@"\<(?<name>\S+)\>", RegexOptions.IgnoreCase);
string name = e.Match.Groups["name"].Value;

But in some cases where I have text like :

<Vendors><Vtitle/>  <VSurname/></Vendors> 

It's returning two strings instead of four, i.e. above Regex outputs

<Vendors><Vtitle/> //as one string and 
<VSurname/></Vendors> //as second string

Where as I am expecting four strings:

<Vendors>
<Vtitle/>
<VSurname/>
</Vendors> 

Could you please guide me what change I need to make to my Regex.

I tried adding '\b' to specify word boundry

new Regex(@"\b\<(?<name>\S+)\>\b", RegexOptions.IgnoreCase);

, but that didn't help.

3
Is there any good reason not to use an xml parser here?Marc Gravell
Agreed with Marc; use an XML parser. Unless you want to build one.Fragsworth
Are you parsing an XML document or do you have angle bracket tags inside a mostly plain text document? XML parsers are particular about having well formatted XML documents. They wouldn't work for finding a few angle bracket tags sprinkled throughout a text document.CoderDennis
OK, I just saw OP's comment on Andrew's answer. These tags happen to look like XML, but this isn't about parsing XML. This is about finding angle bracket delimited text within a mostly plain text document.CoderDennis
Here is the best ever answer on your question. It have 2302 votes up. stackoverflow.com/questions/1732348/…Vasyl Boroviak

3 Answers

10
votes

You'll get most of what what you want by using the regex /<([^>]*)>/. (No need to escape the angle brackets' as angle brackets aren't special characters in most regex engines, including the .NET engine.) The regex I provided will also capture trailing whitespace and any attributes on the tag--parsing those things reliably is way, way beyond the scope of a reasonable regex.

However, be aware that if you're trying to parse XML/HTML with a regex, that way lies madness

6
votes

Regexes are the wrong tool for parsing XML. Try using the System.Xml.Linq (XElement) API.

4
votes

Your regex is using \S+ as the wildcard. In english, this is "a series of one or more characters, none of which is non-whitespace". In other words, when the regex <(?<name>\S+)> is applied to this string: '`, the regex will match the entire string. angle brackets are non-whitespace.

I think what you want is "a series of one or more characters, none of which is an angle bracket".

The regex for that is <(?<name>[^>]+)> .

Ahhh, regular expressions. The language designed to look like cartoon swearing.