0

I currently have the code below, to replace a characters in a string but I now need to replace characters within the first X (in this case 3) characters and leave the rest of the string. In my example below I have 51115 but I need to replace any 5 within the first 3 characters and I should end up with 61115.

My current code:

value = 51115;
oldString = 5;
newString = 6;

result = Regex.Replace(value.ToString(), oldString, newString, RegexOptions.IgnoreCase);

result is now 61116. What would you suggest I do to query just the first x characters?

Thanks

5 Answers 5

2

Not particularly fancy, but only give regex the data it should be replacing; only send in the range of characters that should potentially be replaced.

result = Regex.Replace(value.ToString().Substring(0, x), oldString, newString, RegexOptions.IgnoreCase);
Sign up to request clarification or add additional context in comments.

Comments

1

If you're just replacing a single character only, you could just write the code to do the replacement yourself. It'd be faster than messing with a substring and then a RegEx replace (which is a waste anyway if you're doing a single-char replacement).

StringBuilder sb = new StringBuilder(oldString.Length);
foreach(char c in oldString) {
  if(c == replaceFrom) { c = replaceTo; }
  sb.Append(c);
}
return sb.ToString();

Comments

1

I think the character-by-character option mentioned here is probably clearer, but if you really want a regex:

string result = "";
int value = 55555;
string oldString = "5";
string newString = "6";

var match = new Regex(@"(\d{1,3})(\d+)?").Match(value.ToString());
if (match.Groups.Count > 1)
    result = match.Groups[1].Value.Replace(oldString, newString) + (match.Groups.Count > 2 ? match.Groups[2].Value : "");

Comments

0

I love RegEx, but in this case I would just do a .Replace

    string value;
    string oldString;
    string newString;
    value = "51115";
    int iLenToLook;
    iLenToLook = 3;
    oldString = "5";
    newString = "6";
    string result;
result =  value.Length  > iLenToLook ? value.Substring(iLenToLook, value.Length - iLenToLook) :"";

result = value.Substring(0, value.Length >= iLenToLook ? iLenToLook : value.Length).Replace(oldString, newString) + result;

EDIT I changed it to get the non-replaced portion first, in case there were replacement strings of differing lengths than the original.

Comments

0

Every time someone in the .NET world has a question about regex, I recommend Expresso (link). It's a great tool for working in the confusing and thorny world of regular expressions.

Comments

Your Answer

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