Link to home
Start Free TrialLog in
Avatar of bamapie
bamapie

asked on

c# regex: extract & replace text between braces

So, I am parsing text in C# that is formatted like so:

WEEK_OF_{%yyyy-MM%}

I need to extract what is between {%...%}, format a date according to its date-format spec, and then replace the {%...%} with my result.  So, in the above example, the result might look like:

WEEK_OF_2016_05

I canNOT count on the "WEEK_OF_" portion being constant.  There may be text following the {%...%} area as well.

The only thing I can count on is, there will be a pair of {%...%} braces somewhere in the text.

How can I extract the date format string within these braces, and replace that string (and its braces) with the result?

Thanks.  Always grateful for you regex-minded folks.
Avatar of Pawan Kumar
Pawan Kumar
Flag of India image

Try..

private void Form1_Load(object sender, EventArgs e)
        {
            string pawan = "WEEK_OF_{%2016_05%}";
            string result = pawan.Substring(pawan.IndexOf("%") + 1, pawan.IndexOf("%", (pawan.IndexOf("%") + 1)) - (pawan.IndexOf("%") + 1));
        }


Output
----------------

User generated image
SOLUTION
Avatar of kaufmed
kaufmed
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of bamapie
bamapie

ASKER

Loved the code, but loved the explanation too.  Split the points, hope that's okay.  Appreciated both answers.
Hi,
Any feedback for my code?
Thanks in advance.

Regards,
Pawan
Avatar of bamapie

ASKER

pawan, it was easier for me to understand this problem as needing a regex solution.

Additionally, while your code extracted the string, I did not see code related to replacing it back into the source string.