Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested Regex Replace in C#

Tags:

c#

regex

I'm not really that good with regex, but I understand the basics. I'm trying to figure out how to do a conditional replace based upon a certain value in the match. For example:

Suppose I have some nested string structure that look like this:

"[id value]"//id and value are space delimited.  id will never have spaces

id is some string id that names the [] item and value is another nested [id value] item. Its possible for value to be empty, but I'm not worried about that for now.

If I have something like this:

A) "[vehicle [toyota camry]]"
or
B) "[animal [dog rufus]]"

I'd like to be able to call a certain function (ToString() for example) based upon id that gets output as the regex.Replace is executed from the inner most [] structure.

Going from example A pseudo code:

string Return = "{0}";
var 1stValueComboID = GetInteriorValue/IDFrom("[vehicle [toyota camry]]");
//1stValueComboID.ToString() = "Company: Toyota, Make: Camry"

Return = Format.String(Return,1stValueIDCombo.ToString());


var 2stValueComboID = GetSecondValue/IDFrom("[vehicle [toyota camry]]");
//2stValueComboID.ToString() = "Type: Vehicle, {0}"

Return = Format.String(Return,2ndValueIDCombo.ToString());

This sample obviously has nothing to do with regex, but it hopefully illustrates kind of what I'm trying to do.

like image 411
Shawn Avatar asked Sep 03 '26 22:09

Shawn


1 Answers

Do I understand you correctly, that all strings you want to parse have the form

[id1 [id2 [id3 [id4 .. value]] ... ],

i.e. all brackets are closing at the end? Your question and examples seem to point that way. If thats true, parsing it using regex it not that difficult, depending on what you actually need your parser to do.

You could, say, use

static Tuple<String, String> Parse(String s)
{

    var match = Regex.Match(s, @"^\[(\w*) (.*)\]$", RegexOptions.None);
    return new Tuple<String, String>(match.Groups[1].ToString(), match.Groups[2].ToString());
}

That would result in

var result = Parse("[animal [dog rufus]]");
// result = {Item 1 = "animal", Item2 = "[dog rufus]" }
var inner = Parse(result.Item2);
// inner = { Item 1 = "dog", Item2 ="rufus"}

You could call Parse recursivly to get to the inner nesting levels.

Please ask if you have requirements I did not understand =)

like image 147
Jens Avatar answered Sep 05 '26 12:09

Jens



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!