I have a string like XXXXmakeXXmodel nameXXageXX**** for a car data. I want to get make, model name and age.
So can I split this using regex or another way in c#?
You can convert the string to an array of keyword / value based on key words
for example: XXXXmakeXXmodel
Identify that it does not start with a keyword
Take the value before the keyword
Take the keyword
repeat until you have processed the entire string.
You need to use the String.IndexOf and Substring methodes.
You can split string using Split() function with a delimiter i.e. "XX".
var input = "XXXXmakeXXmodel nameXXageXX****";
//Split string by "XX" and remove empty entries
var array = input.Split("XX", StringSplitOptions.RemoveEmptyEntries);
//Take first n - 1 elements to avoid last ****
var result = array.Take(array.Length - 1);
//Print expected result.
Console.WriteLine(string.Join(Environment.NewLine, result));
.NET FIDDLE
Related
I'm trying to parse a database and replace ":" with another delimiter such as "+delimiter+". The problem with this is this specific database has a hash:salt combo. Some of the salts contain extra ":"'s and some don't. How would I go about replacing all ":"'s and ignoring the ones in the hashes
Example:
1:john:john#john.com:127.0.0.1:341b4d30d4f5bb31f291633e0c97a8ba:J:|
I want to ignore the colons in:
341b4d30d4f5bb31f291633e0c97a8ba:J:|
But I want to replace the other colons with "+delimiter+"
If your string will always be in the format you've specified:
1:john:john#john.com:127.0.0.1:341b4d30d4f5bb31f291633e0c97a8ba:J:|
You can use the String.Split(Char[], Int32) overload to specify the maximum number of substrings returned. Specify 5 substrings and the final substring will contain the remainder of the input string i.e. the hashed field.
string input = "1:john:john#john.com:127.0.0.1:341b4d30d4f5bb31f291633e0c97a8ba:J:|";
string[] array = input.Split(new char[] { ':' }, 5);
You can then use the String.Join method to concatenate the string array with the desired separator.
string output = String.Join("+delimiter+", array);
The String.Split() method takes a count as its second argument:
string input = "1:john:john#john.com:127.0.0.1:341b4d30d4f5bb31f291633e0c97a8ba:J:|";
string[] fields = input.Split(new[]{ ':' }, 5);
The string fields[4] now holds the value 341b4d30d4f5bb31f291633e0c97a8ba:J:|
To complete the replace operation, apply String.Join to concatenate the strings using the new delimiter:
string result = String.Join("+delimiter+", fields);
I have a instrument which returns me a string value as this
string var = "0,0,0.1987,22.13";
I want to use only the 4th value "22.13". I tried with Trim() and Replace() methods but couldn't exactly get what I want. How to achieve this?
The Split method is the best to use here!
The Split method does what it says on the lid. It splits a string into different parts at a character separator that you specify. e.g. "Hello World".Split(' ') splits the string into a string[] that contains {"Hello", "World"}.
So in this case, you can split the string by ',':
var.Split (',') //Use single quotes! It's of type char
If you want to access the fourth item, use an indexer! (of course)
var.Split(',')[3] //Remember to use 3 instead of 4! It's zero based!
Now you can happily store the string in some variable
string fourthThing = var.Split (',')[3];
Additional Information:
The Split method also has a overload that takes a char and a StringSplitOptions. If you do something like this:
var.Split (',', StringSplitOptions.RemoveEmptyEntries)
Empty entries will be automatically removed! How good!
More information: https://msdn.microsoft.com/en-us/library/system.string.split(v=vs.110).aspx
You can use string Split method
string data = "0,0,0.1987,22.13";
string value = data.Split(',')[3];
To pick up the last element, you can use Split function and Linq as below
string GetLastElement(string data) {
return data.Split(',').Last();
}
We have two strings, string first="abcdeabcde" and string second="cdefgcdefg".
What is the fastest/most typing-efficient way to come up with a third string which would contain only possible characters from first string, e.g. string third="cdecde"?
More formal example:
First string contains characters from set F={a,b,c,d,e}
Second string contains characters S={c,d,e,f,g}
I would like to know how can I quickly derive third string with characters from set S\(S\F)= S intersection F.
i.e. string second containing characters in intersection of the strings.
Second example:
string w="aaabbbccc"
string z="bbbcccddd"
expected result: string y="bbbccc" i.e. second string but with only characters b,c, which were in the first string
Third example:
string a="ABCDABCDBABDBC" - random stuff from aplhabet {A,B,C,D}
string b="CDEDECEDCDE" - random stuff from alphabet {C,D,E}
final string f="CDDCDCD" - deleted all occurences of {E}
string first = "abcdeabcde";
string second = "cdefgcdefg";
string intersection = String.Concat(first.Intersect(second));
string result = String.Concat(first.Where(c => intersection.Contains(c)));
Console.WriteLine(result); //output "cdecde"
Explanation:
The Intersect extension method returns an IEnumerable<char> that contains only the characters that exist in both strings, in order to convert it to a string, the Concat method concatenates all the members and returns the resulting string.
Edit
Now only characters that exist in the intersection should remain in string first
If your are looking for a short solution and performance is not an issue, you may want to try this:
var intersect = first.Intersect(second).ToList();
var result = new String(second.Where(c => intersect.Contains(c)).ToArray());
The String.Intersect() method should do exactly what you are looking for. See more information here.
Example:
var string1 = "abcdefg";
var string2 = "cdekdjdfj";
var intersect = string1.Intersect(string2);
I need to select a part of a string ,suppose i have a string like this :Hello::Hi,
I use this characters :: as a separator, so i need to separate Hello and Hi.I am using C# application form .
I googled it ,i found something like substring but it didn't help me.
Best regards
string.Split is the right method, but the syntax is a little tricky when splitting based on a string versus a character.
The overload to split on a string takes the input as an array of strings so it can be distinquished from the overload that takes an array of characters (since a string can be easily cast to an array of characters), and adds a parameter for StringSplitEntries, which you can set to None to use the default option (include "empty" entries):
string source = "Hello::Hi";
string[] splits = source.Split(new string[] {"::"}, StringSplitOptions.None);
You can split a string into multiple parts based on a semaphore using the Split function:
var stringToSearch = "Hello::Hi";
var foundItems = stringToSearch.Split(new[] {"::"},
StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < foundItems.Count(); i++)
{
Console.WriteLine("Item #{0}: {1}", i + 1, foundItems[i]);
}
// Ouput:
// Item #1: Hello
// Item #2: Hi
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();