1

I have a string(numbers only) and I want to replace a specific number with string.Empty. I am using string.Replace but the issue is it replaces the given number from all numbers. I've also tried Regex.Replace but getting same result.

For example,

Code:

string original = "301, 3301, 2301, 5301, 8301";
string modified = original.Replace("301", string.Empty);
string usingRegex = Regex.Replace(original, "301", string.Empty);

Actual Result:

", 3, 2, 5, 8"

Expected Result:

"3301, 2301, 5301, 8301"
5
  • 2
    Split on , , remove the ones you don't want (easy with LINQ), then string.Join the rest back together. Commented Apr 1, 2016 at 16:48
  • 4
    You have a string of numbers? Why not split this into an array of integers? Commented Apr 1, 2016 at 16:49
  • 1
    convert them all to numbers and get rid of 301 .. that should work right? Commented Apr 1, 2016 at 16:50
  • 1
    Regex is probably overkill for such a simple case Commented Apr 1, 2016 at 16:50
  • @zimdanen That's what I was looking for. Thank you Commented Apr 1, 2016 at 16:56

5 Answers 5

1
const string original = "301, 3301, 2301, 5301, 8301, 301";
var lst = original.Split (',').Select(s => s.Trim()).Where(item => item != "301");
var replaced = string.Join(", ", lst);

This splits the string, and removes only those entries that are exactly 301, and joins back up the result. This is broadly a process of tokenization.

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

Comments

1

Try:

string usingRegex = Regex.Replace(original, "(^301 ,|, 301)", string.Empty);

This matches a 301 that ends with , or ends with ,.

Comments

0

Try with \b in your Regex something like this:

string original = "301, 3301, 2301, 5301, 8301";
string modified = original.Replace("301", string.Empty);
string usingRegex = Regex.Replace(original, @"\b301\b", string.Empty);

let me know if this was helpful.

Comments

0

You can try like this,

string pattern = @"\b301\b";
string input = "301, 3301, 2301, 5301, 8301";
string result = Regex.Replace(input, pattern, string.Empty, RegexOptions.None).TrimStart(',');

Comments

0

Not very nice, but working and with Regex. Deletes (!) any number from the given string.

string original = "301, 3301, 2301, 5301, 8301";
string usingRegex = Regex.Replace(original, "(, 5301)*(^5301, )*", "");
Console.WriteLine(original);
Console.WriteLine(usingRegex);

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.