-1

Below is a tiny method to basically replace the word "Stack" with ".png" in a string. So something called "Grid01Stack" would return as "Grid01.png" however the operation doesn't do anything at all, the string remains the same. What is going wrong? Here is the code:

private string GetUriFromName(string GridName)
    {            
        string result = Regex.Replace(GridName, @"\bStack\b", ".png");
        return (@"Resources/Images/"+result);
    }
Astralogic
  • 33
  • 5

3 Answers3

1

\bStack**\b** - is looking for the whole word 'Stack' with spaces, tab, line break, etc before and after word.

You just need the String.Replace for you case.

1

While you can simply do, per Yuri and Cid's suggestions:

GridName.Replace("Stack",".png")

This is not the best option if the word 'Stack' will ever appear more than once in the string, as it will replace all instances. So, for example, "Stack01Stack" will become ".png01.png". As you are trying to form a good filename, you really only want to replace the last occurence of "Stack" with ".png", and only if it at the end of the string. Therefore, using "Stack\b" as the comments suggested could end up messing with valid filenames as well, if Stack shows up multiple times. For instance, using that Regex "GridStack-01Stack" will become "Grid.png-01.png"

This is all based on speculation of what these strings might be, so this solution might not be necessary, but I'd recommend the following Regex, which will only change the word Stack if it occurs at the end of the string:

string result = Regex.Replace(GridName, "Stack$", ".png");
Cid
  • 14,968
  • 4
  • 30
  • 45
Zaelin Goodman
  • 896
  • 4
  • 11
1

• String replace: string x = "Grid01Stack".Replace("Stack", ".png");

• Regex: string x = Regex.Replace("Grid01Stack", "[Ss]tack$", ".png"); The regex will search for Stack or stack which are always in the end of the string.

JohnyL
  • 6,894
  • 3
  • 22
  • 41