1

In c#, I am trying to replace any string between two given strings, primarily using Regex. For example, if I have:

TextBlock Text="this is a test"

Then I want to change it to:

TextBlock Text="Any given string comes here"

For that, after some search, I tried this method:

Regex.Replace(inputString, @"(?<=TextBlock Text=\")(\w+?)(?=\")", "Any given string comes here");

But I've got many errors, saying "An object reference is required for non-static field, method or property". Is there any efficient way to do this with Regex? Thanks.

2
  • 1
    When you prefix the string with the "at" sign (@) you need to escape double quotes as "", not \". Commented Nov 11, 2014 at 14:41
  • 1
    Regex.Replace is a static method, he's using it fine. Though he' not using the return value in his example. Commented Nov 11, 2014 at 14:45

3 Answers 3

1

Instead of (\w+?) in your regex you need to use:

([\w ]+)

To match words separated by space.

Or better you can use negation:

([^"]+)

Which means match 1 or more characters of anything but a double quote.

Your code would be:

Regex.Replace(inputString, 
      @"(?<=TextBlock Text="")([^""]+)(?="")", "Any given string comes here");
Sign up to request clarification or add additional context in comments.

2 Comments

I also tried your method, but with some change as dasblinkenlight and Ed Gibbs mentioned. I need to escape the double quotes with ", then your code works fine. Thanks.
Ah ok I fixed escaping but I believe regex part was correct in my answer.
1

It looks like the problem is that you are trying to escape double-quotes inside your verbatim strings. This is not how it is done: you need to double your double-quotes inside such strings, like this:

@"(?<=TextBlock Text="")(\w+?)(?="")"

When you try escaping a double-quote with a slash, the parser gets confused, because it treats the double-quote as the end of the string. The characters after it produce syntax errors.

Note: with this error out of the way, consider fixing the catastrophic backtracking issue in your regex pattern.

Comments

1

You have three problems that cause this to not work as expected.

  1. You are not assigning your replacement to anything.
  2. You need to double your double quotes inside of your pattern instead of escaping them.
  3. You need to account for whitespace between the words.

String result = Regex.Replace(inputString, @"(?<=TextBlock Text="")[\w\s]+(?="")", "Any given string comes here");

Ideone Demo

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.