How to remove number character from string in c# [duplicate] - c#

This question already has answers here:
How to remove the exact occurence of characters from a string?
(7 answers)
Closed 6 years ago.
i have a string like string st ="12,34,56,345,12,45" and i want remove number 34 from this string i did like string newst = st.replace(",34",""); but it is removing 34 from 345 , how to prevent this
EDIT
34 can be anywhere,here i am generating dynamically

It's very simple:
var st ="12,34,56,345,12,45";
var newst = st.replace(",34,", ",");
If it can be anywhere, you may use the regular expression:
var input = "34,234,35,36,34,37,345,34";
var pattern = #",?\b34\b,?";
var regex = new Regex(pattern);
var result = regex.Replace(input, ",").Trim(',');
Shorter notation could look like this:
var result = Regex.Replace(input, #",?\b34\b,?", ",").Trim(',');
Explanation of the regular expression: ,?\b34\b,? matches the word 34, but only if preceded and followed by word-delimiter characters (because of the word boundary metacharacter \b), and it can be (but doesn't have to be) preceded and followed by the comma thanks to ,? which means none or more comma(s).
At the end we need to remove possible commas from the beginning and end of the string, that's why there's Trim(',') on the result.
But I would say #crashmstr's solution is better than trying to tune the regular expression for this particular use case.

This will work:
var oldString = "34,12,34,56,345,12,45,34";
var newString = String.Join(",", oldString.Split(',').Where(x => x != "34"));
We split on ',', use LINQ to exclude "34", then join the string back together by ','.

Try this
string newst = st.replace(",34,",",");
Granted this only works if the number you want to replace is between two commas. If you want something more advanced, use Regex.Replace()
Here's an example:
string temp = Regex.Replace("12,34,56,345,12,45", #"^34,", "");
string newst = Regex.Replace(temp, #"34$,", "");
You could also use String.TrimStart and .TrimEnd to clean up the borders.
Also, I like crashmstr's example.

split and work in list:
string[] arr = st.Split(',');
List<string> list = arr.ToList();
list.Remove("34");
or regex:
var replaced = Regex.Replace(st, #"\b34\b[,]","");

Related

splitting the string and choosing the middle part containing two set of parenthesis [duplicate]

This question already has answers here:
How do I extract text that lies between parentheses (round brackets)?
(19 answers)
Closed 7 years ago.
As I know for selecting a part of a string we use split. For example, if node1.Text is test (delete) if we choose delete
string b1 = node1.Text.Split('(')[0];
then that means we have chosen test, But if I want to choose delete from node1.Text how can I do?
Update:
Another question is that when there are two sets of parenthesis in the string, how one could aim at delete?. For example is string is test(2) (delete) - if we choose delete
You can also use regex, and then just remove the parentheses:
resultString = Regex.Match(yourString, #"\((.*?)\)").Value.
Replace("(", "").Replace(")", "");
Or better:
Regex.Match(yourString, #"\((.*?)\)").Groups[1].Value;
If you want to extract multiple strings in parentheses:
List<string> matches = new List<string>();
var result = Regex.Matches(yourString, #"\((.*?)\)");
foreach(Match x in result)
matches.Add(x.Groups[1].Value.ToString());
If your string is always xxx(yyy)zzz format, you can add ) character so split it and get the second item like;
var s = "test (delete) if we choose delete";
string b1 = s.Split(new[] { '(', ')' })[1];
string tmp = node1.Text.Split('(')[1];
string final = tmp.Split(')')[0];
Is also possible.
With the index [x] you target the part of the string before and after the character you have split the original string at. If the character occurs multiple times, your resulting string hat more parts.

Remove characters between different parameters [duplicate]

This question already has an answer here:
Learning Regular Expressions [closed]
(1 answer)
Closed 7 years ago.
I have a string of different emails
ex: "email1#uy.com, email2#iu.it, email3#uu.edu" etc, etc
I would like to formulate a Regex that creates the following output
ex: "email1,email2,email3" etc, etc
How can I remove characters between an "#" and "," but leaving a "," and a Space in C#
Thank you so much for the help!!
If you want to replace all characters between # and comma by blank, the easiest option is to use Regex.Replace:
var emails = "a#m.com, b#m.com, d#m.com";
var result = Regex.Replace(emails, "#[^,]+", string.Empty);
// result is "a, b, d"
Please note that it leaves spaces after comma in the result, as you wanted in your question, though your example result has spaces removed.
The regular expression looks for all substrings starting '#' characters, followed by any character which is not comma. Those substrings are replaced with empty string.
Replacing all occurrences of #[^,]+ with an empty string will do the job.
The expression matches sequences that start in #, inclusive, up to a comma or to the end, exclusive. Therefore, commas in the original string of e-mails would be kept.
Demo.
Maybe you don't need to use a regex, in that case you can do the following:
string input = "email1#uy.com, email2#iu.it, email3#uu.edu";
input = input.Replace(" ", "");
string[] ocurrences = input.Split(',');
for (int i = 0; i < ocurrences.Length; i++)
{
string s = ocurrences[i];
ocurrences[i] = s.Substring(0, s.IndexOf('#'));
}
string final = string.Join(", ", occurences);

Omit unnecessary parts in string array

In C#, I have a string comes from a file in this format:
Type="Data"><Path.Style><Style
or maybe
Type="Program"><Rectangle.Style><Style
,etc. Now I want to only extract the Data or Program part of the Type element. For that, I used the following code:
string output;
var pair = inputKeyValue.Split('=');
if (pair[0] == "Type")
{
output = pair[1].Trim('"');
}
But it gives me this result:
output=Data><Path.Style><Style
What I want is:
output=Data
How to do that?
This code example takes an input string, splits by double quotes, and takes only the first 2 items, then joins them together to create your final string.
string input = "Type=\"Data\"><Path.Style><Style";
var parts = input
.Split('"')
.Take(2);
string output = string.Join("", parts); //note: .net 4 or higher
This will make output have the value:
Type=Data
If you only want output to be "Data", then do
var parts = input
.Split('"')
.Skip(1)
.Take(1);
or
var output = input
.Split('"')[1];
What you can do is use a very simple regular express to parse out the bits that you want, in your case you want something that looks like this and then grab the two groups that interest you:
(Type)="(\w+)"
Which would return in groups 1 and 2 the values Type and the non-space characters contained between the double-quotes.
Instead of doing many split, why don't you just use Regex :
output = Regex.Match(pair[1].Trim('"'), "\"(\w*)\"").Value;
Maybe I missed something, but what about this:
var str = "Type=\"Program\"><Rectangle.Style><Style";
var splitted = str.Split('"');
var type = splitted[1]; // IE Data or Progam
But you will need some error handling as well.
How about a regex?
var regex = new Regex("(?<=^Type=\").*?(?=\")");
var output = regex.Match(input).Value;
Explaination of regex
(?<=^Type=\") This a prefix match. Its not included in the result but will only match
if the string starts with Type="
.*? Non greedy match. Match as many characters as you can until
(?=\") This is a suffix match. It's not included in the result but will only match if the next character is "
Given your specified format:
Type="Program"><Rectangle.Style><Style
It seems logical to me to include the quote mark (") when splitting the strings... then you just have to detect the end quote mark and subtract the contents. You can use LinQ to do this:
string code = "Type=\"Program\"><Rectangle.Style><Style";
string[] parts = code.Split(new string[] { "=\"" }, StringSplitOptions.None);
string[] wantedParts = parts.Where(p => p.Contains("\"")).
Select(p => p.Substring(0, p.IndexOf("\""))).ToArray();

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 (_).

Best way to get all digits from a string [duplicate]

This question already has answers here:
return only Digits 0-9 from a String
(8 answers)
Closed 3 years ago.
Is there any better way to get take a string such as "(123) 455-2344" and get "1234552344" from it than doing this:
var matches = Regex.Matches(input, #"[0-9]+", RegexOptions.Compiled);
return String.Join(string.Empty, matches.Cast<Match>()
.Select(x => x.Value).ToArray());
Perhaps a regex pattern that can do it in a single match? I couldn't seem to create one to achieve that though.
Do you need to use a Regex?
return new String(input.Where(Char.IsDigit).ToArray());
Have you got something against Replace?
return Regex.Replace(input, #"[^0-9]+", "");
You'll want to replace /\D/ (non-digit) with '' (empty string)
Regex r = new Regex(#"\D");
string s = Regex.Replace("(123) 455-2344", r, "");
Or more succinctly:
string s = Regex.Replace("(123) 455-2344", #"\D",""); //return only numbers from string
Just remove all non-digits:
var result = Regex.Replace(input, #"\D", "");
In perl (you can adapt this to C#) simply do
$str =~ s/[^0-9]//g;
I am assuming that your string is in $str. Basic idea is to replace all non digits with '' (i.e. empty string)

Categories

Resources