C# Replace group of numbers in a string with a single character - c#

Does anybody know I can replace a group of numbers in a string by one *. For example if I have a string like this "Test123456.txt", I want to convert it to "Test#.txt". I have seen plenty of examples that can replace each individual number with a new character, but none that deal with a group of numbers. Any help is much appreciated!

Regex r = new Regex(#"\d+", RegexOptions.None);
Console.WriteLine(r.Replace("Test123456.txt", "#"));
Console.Read();

Use Regex.Replace() as follows:
string fileName = "Test12345.txt";
string newFileName = Regex.Replace(fileName, #"[\d]+", "#");

you can use regex, to do this, but if you know the exact text, then using the string.Replace method would be more efficient:
string str = "blahblahblahTest123456.txt";
str = string.Replace("Test#.txt","Test123456.txt");

Related

Use regex to find string between 1st and 2nd Comma in a string in C# [duplicate]

I want to extract only those words between two commas.
So, if the string is Ab Java, DE, 78801 The answer must be DE
I have tried this code but it is not working
string search = "Ab Java, DE, 78801 ";
int index = search.IndexOf(",");
string result = search.Substring(search.IndexOf(",") ,index);
MessageBox.Show(result);
If your string has always 2 commas, you can use String.Split for it like;
string search = "Ab Java, DE, 78801 ";
Console.WriteLine(search.Split(',')[1]); // DE
Remember, this will you generate DE with an extra white space before it.
If you don't want that white space, you can use TrimStart() to remove it.
Console.WriteLine(search.Split(',')[1].TrimStart()); //DE
Your start and end in your Substring resolve to the same value.
Try using split and getting the second item, of course this assumes that your input always follows the pattern in your example. Otherwise you'll need to do something more complicated.
string[] searchItems = search.Split(',');
string result = searchItems[1].Trim(); // will output DE
try this
string[] splitedStr=search.Split(',');
string NewStr=splitedStr[1].ToString();
Assuming your string always has just two commas, then:
search.Split(", ")[1]
will give you the desired text.
Try this...
String str = "Ab Java, DE, 78801 ";
String[] myStrings = str.split(",");
String marco = myStrings[1];
Try This. It May work...
string[] arrayStr = search.Split(',');
int len = arrayStr.Length;
for(int i =1;i<=len-2;i++)
{
MessageBox.Show(result);
}
That is something I would have solved using regular expressions. It might be slower than the String.Split solutions but it is way easier to read - in particular if the pattern is going to evolve over time.
The solution would than look like this:
string search = "Ab Java, DE, 78801 ";
Regex r = new Regex(", *(.*?) *,", RegexOptions.Compiled);
Console.WriteLine(r.Match(search).Groups[1].ToString());
This writes DE without surrounding spaces. The regex instance should be a static member of your class, since I assume this is happening within a loop ...

Regex to match only numbers , no apostrophes

I want to match only numbers in the following string
String : "40’000"
Match : "40000"
basically tring to ignore apostrophe.
I am using C#, in case it matters.
Cant use any C# methods, need to only use Regex.
Replace like this it replace all char excpet numbers
string input = "40’000";
string result = Regex.Replace(input, #"[^\d]", "");
Since you said; I just want to pick up numbers only, how about without regex?
var s = "40’000";
var result = new string(s.Where(char.IsDigit).ToArray());
Console.WriteLine(result); // 40000
I suggest use regex to find the special characters not the digits, and then replace by ''.
So a simple (?=\S)\D should be enough, the (?=\S) is to ignore the whitespace at the end of number.
DEMO
Replace like this it replace all char excpet numbers and points
string input = "40’000";
string result = Regex.Replace(input, #"[^\d^.]", "");
Don't complicate your life, use Regex.Replace
string s = "40'000";
string replaced = Regex.Replace(s, #"\D", "");

.NET regex replace using backreference

I have a fairly long string that contains sub strings with the following format:
project[1]/someword[1]
project[1]/someotherword[1]
There will be about 10 or so instances of this pattern in the string.
What I want to do is to be able to replace the second integer in square brackets with a different one. So the string would look like this for instance:
project[1]/someword[2]
project[1]/someotherword[2]
I''m thinking that regular expressions are what I need here. I came up with the regex:
project\[1\]/.*\[([0-9])\]
Which should capture the group [0-9] so I can replace it with something else. I'm looking at MSDN Regex.Replace() but I'm not seeing how to replace part of a string that is captured with a value of your choosing. Any advice on how to accomplish this would be appreciated. Thanks much.
*Edit: * After working with #Tharwen some I have changed my approach a bit. Here is the new code I am working with:
String yourString = String yourString = #"<element w:xpath=""/project[1]/someword[1]""/> <anothernode></anothernode> <another element w:xpath=""/project[1]/someotherword[1]""/>";
int yourNumber = 2;
string anotherString = string.Empty;
anotherString = Regex.Replace(yourString, #"(?<=project\[1\]/.*\[)\d(?=\]"")", yourNumber.ToString());
Matched groups are replaced using the $1, $2 syntax as follows :-
csharp> Regex.Replace("Meaning of life is 42", #"([^\d]*)(\d+)", "$1($2)");
"Meaning of life is (42)"
If you are new to regular expressions in .NET I recommend http://www.ultrapico.com/Expresso.htm
Also http://www.regular-expressions.info/dotnet.html has some good stuff for quick reference.
I've adapted yours to use a lookbehind and lookahead to only match a digit which is preceded by 'project[1]/xxxxx[' and followed by ']':
(?<=project\[1\]/.*\[)\d(?=\]")
Then, you can use:
String yourString = "project[1]/someword[1]";
int yourNumber = 2;
yourString = Regex.Replace(yourString, #"(?<=project\[1\]/.*\[)\d(?=\]"")", yourNumber.ToString());
I think maybe you were confused because Regex.Replace has lots of overloads which do slightly different things. I've used this one.
If you want to process the value of a captured group before replacing it, you'll have to separate the different parts of the string, make your modifications and put them back together.
string test = "project[1]/someword[1]\nproject[1]/someotherword[1]\n";
string result = string.Empty;
foreach (Match match in Regex.Matches(test, #"(project\[1\]/.*\[)([0-9])(\]\n)"))
{
result += match.Groups[1].Value;
result += (int.Parse(match.Groups[2].Value) + 1).ToString();
result += match.Groups[3].Value;
}
If you just want to replace text verbatim, it's easier: Regex.Replace(test, #"abc(.*)cba", #"cba$1abc").
you can use String.Replace (String, String)
for example
String.Replace ("someword[1]", "someword[2]")

How can I use RegEx (Or Should I) to extract a string between the starting string '__' and ending with '__' or 'nothing'

RegEx has always confused me.
I have a string like this:
IDE\DiskDJ205GA20_____________________________A3VS____\5&1003ca0&0&0.0.0
Or Sometimes stored like this:
IDE\DiskSJ305GA23_____________________________PG33S\6&2003Sa0&0&0.0.0
I want to get the 'A3VS' or 'PG33S' string. It's my firmware and is varied in length and type. I used to use:
string[] split = PNP.Split('\\'); //where PHP is my string name
var start = split[1].LastIndexOf('_');
string mystring = split[1].Substring(start + 1);
But that only works for strings that don't end with __ after the firmware string. I noticed that some have an additional random '_' after it.
Is RegEx the way to solve this? Or is there another way better
just without RegEx it can be expressed like this:
var firmware = PNP.Split(new[] {'_'}, StringSplitOptions.RemoveEmptyEntries)[1].Split('\\')[0];
string s = split[1].TrimEnd('_');
string mystring = s.Substring(s.LastIndexOf('_') + 1);
If you want the RegEX way to do it here it is:
Regex regex = new Regex(#"\\.*_+(?<firmware>[A-Za-z0-9]+)_*\\");
var m1 = regex.Match("IDE\DiskSJ305GA23_____________________________PG33S\6&2003Sa0&0&0.0.0");
var g1 = m1.Groups["firmware"].Value;
//g1 == "PG33S"
Keep in mind you have to use [A-Za-z0-9] instead of \w in the capture subexpression since \w also matches an underscore (_).

Remove alphabets from a string

I want to remove alphabets from a string. What is the best way to do it. To be more precise, i have MAC address of a system, and I want to extract only the numbers from it. I have found this article or stackoverflow. link text
I want to know, if using the regex is the best way or there are other ways to do it (maybe using LINQ).
To get the digits, you can use this regex:
var digits = Regex.Replace(text, #"\D", "");
\D matches anything that is not a digit, so removing those will give you the remaining digits.
The LINQ approach would be as follows:
string input = "12-34-56-78-9A-BC";
string result = new String(input.Where(Char.IsDigit).ToArray());
Non-LINQ / 2.0 approach:
string result = new String(Array.FindAll(input.ToCharArray(),
delegate(char c) { return Char.IsDigit(c); }));
This will replace anything that's not a number and leave you with just numbers:
string text = "abc123abc:13sdf2";
string numbers = Regex.Replace(text, #"[^\d]+", "");
Console.WriteLine(numbers);

Categories

Resources