Click here to Skip to main content
15,902,276 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi, I have a string with some keyword and values follow. I want to get value after keyword using Regex. For example in this case. I want to get values of class and student.

KEYSTRING
<Tag
  <A "SCHOOL">
  <Tag
    <Tag
      <A "CLASSID">
      <A "A01">
    >
    <Tag
      <A "STUDENTID">
      <A "SB1234">
    >
  >
>.


I want value ClassID is <A "A01"> and StudentID is <A "SB1234">
I have tried this regex, but the result not pretty.

Demo regex

What I have tried:

I tried with this Regex
var _matchClassID = Regex.Match(_str.Replace("\r\n", ""), @"\<A ""CLASSID"">(.*?)\"">");
var _matchStudentID = Regex.Match(_str.Replace("\r\n", ""), @"\<A ""STUDENTID"">(.*?)\"">");
//// I want value like this 
//// ClassID is   <A "A01">   and StudentID is   <A "SB1234">
Posted
Updated 5-Aug-23 2:51am
Comments
PIEBALDconsult 5-Aug-23 11:12am    
If the string is XML, use XPath.

Try this:
string regex = "(\\<A\\s\"CLASSID\"\\>.*?\"(?<ClassID>.*?)\").*?(\\<A\\s\"STUDENTID\"\\>.*?\"(?<StudentID>.*?)\")";
            string input = "KEYSTRING\r\n<Tag\r\n  <A \"SCHOOL\">\r\n  <Tag\r\n    <Tag\r\n      <A \"CLASSID\">\r\n      <A \"A01\">\r\n    >\r\n    <Tag\r\n      <A \"STUDENTID\">\r\n      <A \"SB1234\">\r\n    >\r\n  >\r\n>.";
            Match matched = Regex.Match(input, regex, RegexOptions.Singleline);
            if (matched.Success)
                {
                Console.WriteLine($"{matched.Groups["ClassID"].Value}:{matched.Groups["StudentID"].Value}");
                }
 
Share this answer
 
Comments
headshot9x 5-Aug-23 8:53am    
It's look good, I have other idea also, see my answer :]]
Oh, After look at some idea from OriginalGriff. I try spend more time to debug and get like this. Demo link . By the way, all option probably working fine.

var _matchClassID = Regex.Match(input.Replace("\r\n", ""), @"\<A ""CLASSID"">.*?(\<A "".*?"">)");
var _matchStudentID = Regex.Match(input.Replace("\r\n", ""), @"\<A ""STUDENTID"">.*?(\<A "".*?"">)");
 
Share this answer
 
Comments
PIEBALDconsult 6-Aug-23 16:31pm    
Please don't try to answer your own question, just use the Improve question button to add detail.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900