Replacing first part of string by another - c#

I need to replace multiple file names in a folder. Here is one of the files:
Abc.CDE.EFG
I need to replace the first part of the string before the dot ("ABC") and replace it with: "zef".
Any ideas? I found this but it takes out the dot and not sure how to add the "zef".
var input = _FileInfo.ToString();
var output = input.Substring(input.IndexOf(".").Trim())

Since the question is tagged with regex, you can use a regular expression like so:
var input = "abc.def.efg";
var pattern = "^[^\\.]+";
var replacement = "zef";
var rgx = new Regex(pattern);
var output = rgx.Replace(input, replacement);
Source: https://msdn.microsoft.com/en-us/library/xwewhkd1(v=vs.110).aspx

You are almost there, try:
string myString = "Abc.CDE.EFG";
//This splits your string into an array with 3 items
//"Abc", "CDE" and "EFG"
var stringArray = myString.Split('.');
//Now modify the first item by changing it to "zef"
stringArray[0] = "zef";
//Then we rebuild the string by joining the array together
//delimiting each group by a period
string newString = string.Join(".", stringArray);
With this solution you can independently access any of the "blocks" just by referencing the array by index.
Fiddle here

Try this:
var input = _FileInfo.ToString();
var output = "zef" + input.Substring(input.IndexOf("."));

If you know the length of the first string , you can replace mentioning number of characters starting from position until the length you want to replace else.
string s = "Abc.CDE.EFG";
string [] n = s.Split('.');
n[0] = "ZEF";
string p = string.Join(".",n);
Console.WriteLine(p);
}

Related

Need to replace a string C#

I need to replace:
string input = "%someAlphabets%.ZIP"
string replaceWith = "Hello"
string result = "Hello.ZIP"
I tried with Regex.Replace(inputString,"[%][A-Za-z][%]", replacedWith); but it is not working.
The problem in your expression is that, there is only one alphabet in between % signs. You need to repeat the alphabets.
Regex.Replace(inputString,"[%][A-Za-z]{1,}[%]", replacedWith);
Try this:
string input= "%someAlphabets%.ZIP"
string regex = "(%.*%)";
string result = Regex.Replace(input, regex, "Hello");
It doesn't care if the name is alphabet only but that you can change by changing the .* caluse to your selection logic.
As already mentioned in the comments, you don't need RegEx for this.
More simpler alternatives may be:
Using string.Format
string.Format("{0}", input)`
Using string interpolation
var input = "Hello";
var result = $"{input}.zip";
Using string.Replace method
var input = "%pattern%.ZIP"
var with = "Hello"
var result = input.Replace("%pattern%", with);

Split string and print the value of string separately in autocad

534-W1A-R1 this is my file name and I want to split it so it prints like
Code=534 Phase=1 Zone=A
in my Autocad file.
The below split code should work:
string str = #"534-W1A-R1";
var split = str.Split('-');
string code = split.First();
string phase = new string(split.ElementAt(1).Skip(1).Take(1).ToArray());
string zone = new string(split.ElementAt(1).Skip(2).Take(1).ToArray());
string result = String.Format("Code={0} Phase={1} Zone={2}", code, phase, zone);
Console.WriteLine(result);
Output:
Code=534 Phase=1 Zone=A
Use the Substring() method.
string input = "534-W1A-R1";
string sub = input.Substring(0, 3);
string sub2 = input.Substring(5, 1);
string sub3 = input.Substring(6, 1);
Console.WriteLine("Code={0} Phase={1} Zone={2}", sub, sub2, sub3);
Output:
Code=534 Phase=1 Zone=A
You have different ways to do it. if you are sure about the format of the text you can just use this:
var str= "534-W1A-R1";
var parts=str.Split('-');
var code= parts[0];
var secondPart= parts[1];
var phase=secondPart.Substring(1,secondPart.Length-2);
var zone=secondPart[secondPart.Length-1];
You can also use Regex if it is more complicated.
Using Regex
Edit: added some comments (pattern description)
var pattern = #"^(\d+)-[A-Z](\d+)([A-Z])-";
/* pattern description:
^(\d+) group 1: one or more digits at the begining
- one hyphen (literal)
[A-Z] one alphabetic character
(\d+) group 2: one or more digits
([A-Z]) group 3: one alphabetic character
- one hyphen (literal)
*/
var input = "534-W1A-R1";
var groups = Regex.Match(input, pattern, RegexOptions.IgnoreCase).Groups;
var code = groups[1].Value;
var phase = groups[2].Value;
var zone = groups[3].Value;

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();

Multi Substring from long string

I have a long string I need to take out only substrings that are between { and }, and turn it into a Json object
This string
sys=t85,fggh{"Name":"5038.zip","Folder":"Root",,"Download":"services/DownloadFile.ashx?"} dsdfg x=565,dfg
{"Name":"5038.zip","Folder":"Root",,"Download":"services/DownloadFile.ashx?"}dfsdfg567
{"Name":"5038.zip","Folder":"Root",,"Download":"services/DownloadFile.ashx?"}sdfs
I have trash inside so I need to extract the substring of the data between { and }
My code is here, but I'm stuck, I can't remove the data that I already taken.
List<JsonTypeFile> AllFiles = new List<JsonTypeFile>();
int lenght = -1;
while (temp.Length>3)
{
lenght = temp.IndexOf("}") - temp.IndexOf("{");
temp=temp.Substring(temp.IndexOf("{"), lenght+1);
temp.Remove(temp.IndexOf("{"), lenght + 1);
var result = JsonConvert.DeserializeObject<SnSafe.JsonTypeFile>(temp);
AllFiles.Add(result);
}
Or using regex you can get the strings like this:
var regex = new Regex("{([^}]*)}");
var matches = regex.Matches(str);
var list = (from object m in matches select m.ToString().Replace("{",string.Empty).Replace("}",string.Empty)).ToList();
var jsonList = JsonConvert.SerializeObject(list);
The str variable containing your string as you provided in your question.
You can use a regex for this but what I would do is use .split ('{') to split into sections, skip the first section, and then using .split('}) to find the first portion of each section.
You can do this using LINQ
var data = temp
.Split('{')
.Skip(1)
.Select(v => v.Split('}').FirstOrDefault());
If I understand correctly, you just want to extract anything in-between the braces and ignore anything else.
The following regular expression should allow you to extract that info:
{[^}]*} (a brace, followed by anything that isn't a brace, followed by a brace)
You can extract all instances and then deserialize them using something along the lines of:
using System.Text.RegularExpressions;
...
List<JsonTypeFile> AllFiles = new List<JsonTypeFile>();
foreach(Match match in Regex.Matches(temp, "{[^}]*}"))
{
var result = JsonConvert.DeserializeObject<SnSafe.JsonTypeFile>(match.Value);
AllFiles.Add(result);
}

C# how to pick out certain part in a string

I have a string in a masked TextBox that looks like this:
123.456.789.abc.def.ghi
"---.---.---.---.---.---" (masked TextBox format when empty, cannot use underscore X( )
Please ignore the value of the characters (they can be duplicated, and not unique as above). How can I pick out part of the string, say "789"? String.Remove() does not work, as it removes everything after the index.
You could use Split in order to separate your values if the . is always contained in your string.
string input = "123.456.789.abc.def";
string[] mySplitString = input.Split('.');
for (int i = 0; i < mySplitString.Length; i++)
{
// Do you search part here
}
Do you mean you want to obtain that part of the string? If so, you could use string.Split
string s = "123.456.789.abc.def.ghi";
var splitString = s.Split('.');
// splitString[2] will return "789"
You could simply use String.Split (if the string is actually what you have shown)
string str = "123.456.789.abc.def.ghi";
string[] parts = str.Split('.');
string third = parts.ElementAtOrDefault(2); // zero based index
if(third != null)
Console.Write(third);
I've just used Enumerable.ElementAtOrDefault because it returns null instead of an exception if there's no such index in the collection(It falls back to parts[2]).
Finding a string:
string str="123.456.789.abc.def.ghi";
int i = str.IndexOf("789");
string subStr = str.Substring(i,3);
Replacing the substring:
str = str.Replace("789","").Replace("..",".");
Regex:
str = Regex.Replace(str,"789","");
The regex can give you a lot of flexibility finding things with minimum code, the drawback is it may be difficult to write them
If you know the index of where your substring begins and the length that it will be, you can use String.Substring(). This will give you the substring:
String myString = "123.456.789";
// looking for "789", which starts at index 8 and is length 3
String smallString = myString.Substring(8, 3);
If you are trying to remove a specific part of the string, use String.Replace():
String myString = "123.456.789";
String smallString = myString.Replace("789", "");
var newstr = new String(str.where(c => "789")).tostring();..i guess this would work or you can use sumthng like this
Try using Replace.
String.Replace("789", "")

Categories

Resources