Help on C# Regular Expression

  • Thread starter Thread starter Mani Ram
  • Start date Start date
M

Mani Ram

Hi Guys,
I am new to C#. I have a xml string and I want to read a value of a
particular element. I do not want to use dom for this purpose. I think
Regular expression will solve this.

the code snippet goes like this...

string strMsg ="<MyTestXml><First>One</First><Second>Two</Second><Third>Three</Third></MyTestXml>"

Regex re1=new Regex(@"<First>.*?</First>",RegexOptions.IgnoreCase);
string strVal=re1.Match(strMsg).Value;

strVal now contains "<First>One</First>"
How do I read just the value [ in this case, One ] from the
expression. Any help is greatly appreciated.
 
Hello,

Change your pattern to:

@"<First>(.*?)</First>"

and then inspect the Matches collection. The captured value should be
somewhere in the matches (most likely as a sub-match of a match at index 1).

--
Dmitriy Lapshin [C# / .NET MVP]
X-Unity Test Studio
http://x-unity.miik.com.ua/teststudio.aspx
Bring the power of unit testing to VS .NET IDE

Mani Ram said:
Hi Guys,
I am new to C#. I have a xml string and I want to read a value of a
particular element. I do not want to use dom for this purpose. I think
Regular expression will solve this.

the code snippet goes like this...

string strMsg
= said:
Regex re1=new Regex(@"<First>.*?</First>",RegexOptions.IgnoreCase);
string strVal=re1.Match(strMsg).Value;

strVal now contains "<First>One</First>"
How do I read just the value [ in this case, One ] from the
expression. Any help is greatly appreciated.
 
Use this expression:

(?<=<First>).*?(?=</First>)

The (?<=...) and (?=...) constructs are called zero-width positive
look-around assertions because they must be present for a match, but they do
not get included in the match. There are also negative versions (?<!...)
and (?!...).


Brian Davis
www.knowdotnet.com



Mani Ram said:
Hi Guys,
I am new to C#. I have a xml string and I want to read a value of a
particular element. I do not want to use dom for this purpose. I think
Regular expression will solve this.

the code snippet goes like this...

string strMsg
= said:
Regex re1=new Regex(@"<First>.*?</First>",RegexOptions.IgnoreCase);
string strVal=re1.Match(strMsg).Value;

strVal now contains "<First>One</First>"
How do I read just the value [ in this case, One ] from the
expression. Any help is greatly appreciated.
 
Thank you guys for your reply.

I have worked it this way:

string strMsg
="<mytestxml><first>one</first><second>two</second><third>three</third><
/mytestxml>"

string reMsg = "<first" + "[^>]*" + ">" + "(?<contents>.*?)" +
"</first>";

Match m1 = Regex.Match(strMsg, reMsg,RegexOptions.Multiline |
RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);

string s=m1.Groups["contents"].ToString();
 
Back
Top