0

I have the following string, "Last Run: 2011-10-03 13:58:54 (7m 30s ago) [status]" and I would like to replace "7m 30s" (it is not a fixed string) with another string I have generated. How can I do that with string manipulation in C#?

5
  • Is the sample string, static ? Commented Oct 3, 2011 at 12:10
  • Regex.Replace msdn.microsoft.com/en-us/library/xwewhkd1.aspx Commented Oct 3, 2011 at 12:11
  • Why is it important to use the old string instead of creating a new string? Commented Oct 3, 2011 at 15:19
  • Is this a string you created or an input from somewhere else? If you created it why not format it correctly the first time? Some code might help understand what you're doing. Commented Oct 3, 2011 at 16:32
  • 1
    What do you have so far? Commented Oct 3, 2011 at 16:58

10 Answers 10

6
string str = "Last Run : (3m 4s ago) [status]";
str = str.Replace("3m 4s", "yournewstring");

UPDATE :

Ref : Kash's answer.

If time is not fixed, it might be in hour,day, minute and second then regular expression is best choice as it's done by Kash. You can do it like below :

string str = "Last Run: 2011-10-03 13:58:54 (7m 30s  ago) [status]";
string replacement = "test";
string pattern = @"\((.+?)\s+ago\)";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(str, "(" + replacement + " ago)");
MessageBox.Show(result);
Sign up to request clarification or add additional context in comments.

3 Comments

Based on the question, "3m 4s" is not fixed, hence this will not work. We may have to use String.Replace (or Regex) using the pattern for the rest of the string.
@Kash : It was not mentioned by OP in question at the time when I answered.
Sounds great, I didn't realize that this answer was put in before the question update (wish there was a better way to show the timeline of question edits and answers - another thing for metastackoverflow). I have removed my downvote.
3

You should consider using String.Format instead for this

string result = String.Format("Last Run : ({0} ago) [status]", theTime);

This is only if you have control over the string in question.

Comments

1

For the most convenient way to resolve this, use a combination of RegEx and String.Replace like the below code. I am assuming you do not have access to the generation of this input string (Last Run: 2011-10-03 13:58:54 (7m 30s ago) [status]).

It basically has 3 stages:

Locate the pattern:

I am using the braces in the input string and "ago" as the pattern to locate the duration that you need to replace. "((.+?)\s+ago)" is the pattern used. It uses the lazy quantifier "?" to ensure it does minimal matching instead of a greedy match. May not be applicable to your example here but helps if the method will be reused in other scenarios.

Create the backreference group to get the exact substring 7m 30s

Regex.Match uses the pattern and creates the group that will contain "7m 30s". Please note the 1st group is the entire match. The 2nd group is what will be in the braces specified in the pattern which in this case is "7m 30s". This should be good even if later you get a duration that looks like: "Last Run: 2011-10-03 13:58:54 (1d 3h 20m 5s ago) [status]"

Replace the occurence

Then String.Replace is used to replace this substring with your replacement string. To make it more generic, the method Replace below will accept the inputstring, the replacement string, the pattern and the group number of the backreference (in this case only one group) so that you can reuse this method for different scenarios.

    private void button1_Click(object sender, EventArgs e)
    {
        string inputString = "Last Run: 2011-10-03 13:58:54 (7m 30s  ago) [status]";
        string replacementString = "Blah";
        string pattern = @"\((.+?)\s+ago\)";
        int backreferenceGroupNumber = 1;
        string outputString = Replace(inputString, replacementString, pattern, backreferenceGroupNumber);
        MessageBox.Show(outputString);
    }

    private string Replace(string inputString, string replacementString, string pattern, int backreferenceGroupNumber)
    {
        return inputString.Replace(Regex.Match(inputString, pattern).Groups[backreferenceGroupNumber].Value, replacementString);
    }

This has been tested and it outputs "Last Run: 2011-10-03 13:58:54 (Blah ago) [status]".

Notes:

  • You can modify the Replace method appropriately for IsNullOrEmpty checks and/or null checks.
  • The button1_Click was my sample eventhandler that I used to test it. You can extract part of this in your core code.
  • If you do have access to the generation of the input string, then you can control the duration part while you are generating the string itself instead of using this code to replace anything.

1 Comment

it's great answer but i found solution simple way as per posted below in answer section.
1

You can either use the String.Replace method on your string like:

var myString = "Last Run : (3m 4s ago) [status]";
var replacement = "foo";
myString = myString.Replace("3m 4s ago", replacement);

Or probably you want to use a regular expression like:

var rgx = new Regex(@"\d+m \d+s ago");
myString = rgx.Replace(myString, replacement);

The regular expression above is just an example and not tested.

2 Comments

The first solution will not work as "3m 4s" is not constant and will change.
The second solution will not work with the pattern "\d+m \d+s ago", moreover this can have a hour and day component as it shows the duration from the last run. Hence the second solution will not work either.
1

You can try this :

        string s = "Last Run : (3m 4s ago) [status]";
        s = s.Replace("3m 4s", myString);

3 Comments

@Kash : It wasn't specified when I answered ;-)
Ah! Sorry about that. I will remove my downvote after the 2hr limit.
Hi Seb, can you please edit your answer with atleast 6 chars so that I can remove my downvote (StackOverflow is not allowing me to do so without the answer edit).
1

Use String.Replace() function for that and also see the below code.

stirng YourString = "Last Run : (3m 4s ago) [status]";
YourString = YourString.Replace("3m 4s","Your generated String");

2 Comments

Ok, @Downvoters should tell the reason before downvoting. Have guts to say a reason.
Sorry about that, I downvoted because the OP has mentioned that the duration is not static hence your code will not work. However I believe that your answer was put in before a question edit was done. i would like to remove my downvote but stackoverflow needs this answer to be edited (atleast 6 chars) before I can remove my downvote. Can you please change your answer so that I can do that. Thanks
0
string input = "Last Run: 2011-10-03 13:58:54 (7m 30s  ago) [status] ";
string pattern = @"(\d+h \d+m \d+s|\d+m \d+s|\d+s)";
string replacement = "yay";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(input, replacement);

Console.WriteLine("Original String: {0}", input);
Console.WriteLine("Replacement String: {0}", result);  

This is the example of http://msdn.microsoft.com/en-us/library/xwewhkd1.aspx just changed the input and the pattern...

The pattern can be improved because maybe in the input string you only receive the seconds or the hours, minutes and seconds.... Kinda of an improvement in the regex

Comments

0

How about:

Regex.Replace(yourString, @"\(.+\)", string.Format("({0} ago)", yourReplacement));

A bit brute force but should work and is simple.

Explanation

@"\(.+\)" will match a complete pair of brackets with anything between them (so make sure you will only ever have one pair of brackets else this won't work).

string.Format("({0} ago)", yourReplacement) will return "(yourReplacement ago)"

Comments

0

Don't use string.Replace. Just output a new string:

TimeSpan elapsed = DateTime.Now.Subtract(lastRun);
string result =  string.Format("Last Run: {0} ({1} ago) [status]", lastRun, elapsed.ToString("%m'm '%s's'"));

This assumes that the lastRun variable is populated with the last run time.

Comments

0

this.lastrun is the string as I have defined in the question.

this.lastRun = this.lastRun.Replace(this.lastRun.Substring(lastRun.IndexOf("(") + 1, (lastRun.IndexOf(")") - lastRun.IndexOf("(") - 1)) , retstr + " ago");

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.