0

I'm currently doing a bunch of Regex replaces like this

_skeleton = Regex.Replace(_skeleton, "&%currTIME", DateTime.Now.ToString());

Is there any way to make it so I don't have to write '_skeleton ='?

Maybe using 'out'?

3 Answers 3

2

Since strings are immutable, you cannot change their contents. You must create a new string with the contents you want.

Think of it like any other immutable type (DateTime, int, etc.)

int i = 1;
i++; // i = i + 1
i += 2; // i = i + 2

DateTime d = DateTime.Now
d = d.AddDays(1);

string s = "s";
s = s + "tring";

You can wrap the functionality to be a little more functional in nature:

public void MyRegexReplace(ref string mystring, string pattern, string replaceWith)
{
    mystring = Regex.Replace(mystring, pattern, replaceWith);
}

And then call it like:

MyRegexReplace(ref _skeleton, "&%currTIME", DateTime.Now.ToString());

But this doesn't seem that useful to me.

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

1 Comment

Just use mystring as a ref parameter :/
0

If you don't want to have to keep repeating yourself for multiple replacements on the same string, you can nest the calls to Regex.Replace():

_skeleton = Regex.Replace(
                    Regex.Replace(_skeleton, "foo", "bar"),
            "&%currTIME", DateTime.Now.ToString());

(Editing the answer because my response is too long for a comment)

You don't need to even indent them:

_skeleton = Regex.Replace(Regex.Replace(Regex.Replace/*...*/(_skeleton,
            "foo", "bar"),
            "baz", "blaz"),
            //..
            "TIMTOWTDI", "There Is More Than One Way To Do It"
            ));

2 Comments

Unfortunately, I have like 20 replaces. It's unreadable without writing a new line.
@cam: I've put a response to your comment in my original answer, because the comment box is too awkward for it.
0

How about defining:

 void static void RexReplace(ref strTarget, string searchPatter, string replacePattern)
 {
      str = Regex.Replace(str, searchPatter, replacePattern); 
 }

And then write

 RexReplace(ref _skeleton, "&%currTIME", DateTime.Now.ToString());

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.