Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Getting Substring between two different Delimiters

Tags:

c#

regex

split

I have problems splitting this Line. I want to get each String between "@VAR;" and "@ENDVAR;". So at the End, there should be a output of:

Variable=Speed;Value=Fast;
Variable=Fabricator;Value=Freescale;Op==;

Later I will separate each Substring, using ";" as a delimiter but that I guess wont be that hard. This is how a line looks like:

@VAR;Variable=Speed;Value=Fast;Op==;@ENDVAR;@VAR;Variable=Fabricator;Value=Freescale;Op==;@ENDVAR;

I tried some split-options, but most of the time I just get an empty string. I also tried a Regex. But either the Regex was wrong or it wasnt suitable to my String. Probably its wrong, at school we learnt Regex different then its used in C#, so I was confused while implementing.

Regex.Match(t, @"/@VAR([a-z=a-z]*)/@ENDVAR")

Edit:

One small question: I am iterating over many lines like the one in the question. I use NoIdeas code on the line to get it in shape. The next step would be to print it as a Text-File. To print an Array I would have to loop over it. But in every iteration, when I get a new line, I overwrite the Array with the current splitted string. I put the Rest of my code in the question, would be nice if someone could help me.

string[] w ;
foreach (EA.Element theObjects in myPackageObject.Elements)
{
   theObjects.Type = "Object";
   foreach (EA.Element theElements in PackageHW.Elements)
   {
       if (theObjects.ClassfierID == theElements.ElementID)
       {
          t = theObjects.RunState;
          w = t.Replace("@ENDVAR;", "@VAR;").Replace("@VAR;", ";").Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);

          foreach (string s in w)
          {
             tw2.WriteLine(s);
          }
       }
   }
}

The piece with the foreach-loop is wrong pretty sure. I need something to print each splitted t. Thanks in advance.

like image 542
Alika87 Avatar asked Dec 14 '25 12:12

Alika87


2 Answers

you can do it without regex using

str.Replace("@ENDVAR;", "@VAR;")
  .Split(new string[] { "@VAR;" }, StringSplitOptions.RemoveEmptyEntries);

and if you want to save time you can do:

str.Replace("@ENDVAR;", "@VAR;")
  .Replace("@VAR;", ";")
  .Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
like image 134
No Idea For Name Avatar answered Dec 17 '25 04:12

No Idea For Name


You can use a look ahead assertion here.

@VAR;(.*?)(?=@ENDVAR)

If your string never consists of whitespace between @VAR; and @ENDVAR; you could use the below line, this will not match empty instances of your lines.

@VAR;([^\s]+)(?=@ENDVAR)

See this demo

like image 20
hwnd Avatar answered Dec 17 '25 05:12

hwnd