saraswathi
saraswathi

Reputation: 69

String parse in c#

I have a string

 (ProductAttributes,MapType(StringType,StructType(
   List( (CurrentValue,StringType,true), (OldValue,StringType,true), 
   (LastValue,StringType,true))),true),true)

I need to extract StructType(List( (CurrentValue,StringType,true), (OldValue,StringType,true), (LastValue,Stringy )

I've used string.split using separator as "," but I'm not getting the entire struct string.The string I got while using ","

(ProductAttributes

MapType(StringType

StructType(List( (CurrentValue

StringType true)

(OldValue StringType true)

(LastValue StringType true))) true) true)

I can give the count parameter as '3' but my string might change.I tried giving separator as '()' the got the full string .

The expected result is something like this.I can build this string using an object but extracting the values from the string is a blocker for me now

{"FieldId":"401","Name":"CurrentValue","Type":"string","ParentName":"ProductAttributes>CurrentValue","ParentId":"4"}

Another string example would be:

   (BusinessRules,ArrayType(StructType(List( (Id,IntegerType,true), (ErrorCode,IntegerType,true), (Overrides,ArrayType(StructType(List( (OverrideSource,IntegerType,true), (IsOverridden,BooleanType,true), (ReasonId,IntegerType,true), (OverriddenBy,StringType,true), (OverrideDate,LongType,true), (DependencyProductAttributeIds,ArrayType(IntegerType,true),true))),true),true))),true),true)

Upvotes: 0

Views: 111

Answers (1)

Simply Ged
Simply Ged

Reputation: 8642

As stated in the comments it is hard to know how your string might change in the future, but this answer could be used as a starting point (as it will work with the string you have already provided)

You can find the first instance of StructType and then count the number of ( between the start of the string and the found instance. Then count the same number of ) from the end of the string to get your substring.

var stringToParse = @" (ProductAttributes,MapType(StringType,StructType(
   List( (CurrentValue,StringType,true), (OldValue,StringType,true), 
   (LastValue,StringType,true))),true),true)";

var start = stringToParse.IndexOf("StructType(");

var count = stringToParse.Substring(0, start).Count(c => c == '(');

var end = stringToParse.Length;

for(int i = 0; i < count + 1; i++)
{
    end = stringToParse.LastIndexOf(')', end - 1);
}

var result = stringToParse.Substring(start, end - start);

Console.WriteLine(result);

Note: We add 1 to the ( count in the for loop to ensure we count back to the matching ) for our initial search string StructType(

Upvotes: 2

Related Questions