0

I have this code for replace the content between ()

 Regex yourRegex = new Regex(@"\(([^\)]+)\)");

            //Example strings
           string rep1 yourRegex.Replace("This is a (variable) string.", ""); //yields "This is a string."

Result is "This is a string."

but i have this string "This is a [variable] string". Now how to use Regex for same replace method?

3
  • @evanmcdonnal what should be used instead? Commented Dec 5, 2013 at 22:11
  • 1
    @DavidHaney I'm not entirely sure because the OP only provided a finite example. If you're coding for that specific case you should use the plain old String.Replace if you're coding for the general case RegEx has no chance of working and the implementation is far more complicated. To reliably parse a Context Free Language you need some implementation of a PDA (RegEx is an implementation of an NFA). Commented Dec 5, 2013 at 22:32
  • Ahh, I see what you're getting at. You saw (variable) as a keyword of sorts. Fair enough. Commented Dec 5, 2013 at 22:59

1 Answer 1

1

Use

Regex yourRegex = new Regex(@"\(.*\)|\[.*\]");

My version uses only matches, whereas yours uses groups which are a little more expensive and unnecessary for what you're trying to accomplish.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.