I am reading a CSV file and a line reads like this
Context Tenant: {Vendor: 1, Customer: 719046046}","1,664,705.67","","7/11/2017 4:55 PM"
Now i would like to split this and collect each values in a Array.
value[0] should be Context Tenant: {Vendor: 1, Customer: 719046046}
value[1] should be 1,664,705.67
value[2] should be 7/11/2017 4:55 PM.
Tried using Regex and Split
var values = line1.Split(new char[] { '\\', '"' ,','}, StringSplitOptions.RemoveEmptyEntries);
var values = Regex.Split(line1, "\\,");
However i am unable to read the value as i expected. Can you please share some light.
this should do the job. This version will remove the empty spaces
string [] n_new = g.Split(new string[] { "\",\""}, StringSplitOptions.RemoveEmptyEntries)
To get rid of the starting end end " you can put an additional Trim before the Split:
string [] ret = g.Trim('"').Split(new string[] { "\",\""}, StringSplitOptions.RemoveEmptyEntries);
Because some of your elements contains commas I'd suggest splitting specifically on ",", so use this in your split statement: "\",\"". So you should end up with:
var values = Regex.Split(line1, "\",\"");
And then to solve your issues of including " in the results, consider:
foreach (string value in string[] values)
value = value.Replace("\"\"", "");
to get rid of all the unwanted extra double quotes ("). Sort of hacky but it should do the trick.
Related
I have been stuck in a situation .
Here are few input strings -
"abacuses\r\n25"
"alphabet\r\n56,\r\n57"
"animals\r\n44,\r\n45,\r\n47"
I need the output to be splited like -
"abacuses\r\n25" to be splitted into A)abacuses B)25
"alphabet\r\n56,\r\n57" to be splitted into A)alphabet B)56,57
"animals\r\n44,\r\n45,\r\n47" to be splitted into A)animals B)44,45,47
So far I have tried this but it doesn't work-
string[] ina = Regex.Split(indexname, #"\r\n\D+");
string[] ina = Regex.Split(indexname, #"\r\n\");
Please Help
No regex needed in your example. You basicaly parse string:
string input = "animals\r\n44,\r\n45,\r\n47";
var split = input.Split(new char[]{'\r','\n',','}, StringSplitOptions.RemoveEmptyEntries);
var name = split[0]; //animals
var args = string.Join(",", split.Skip(1)); //44,45,37
Many people use it for parsing, but Regex is not a parsing language! It is pattern matcher! It is used to find substrings in string! If you can just Split your string - just do it, really. It is much easier to understand than Regex expression.
If you need to split a string at the first \r\n, you may use a String.Split with a count argument:
var line = "animals\r\n44,\r\n45,\r\n47";
var res = line
.Split(new[] {"\r\n"}, 2, StringSplitOptions.RemoveEmptyEntries);
// Demo output
Console.WriteLine(res[0]);
if (res.GetLength(0) > 1)
Console.WriteLine(res[1].Replace("\r\n", "")); // In the second value, linebreaks should be removed
See the C# demo
The 2 in .Split(new[] {"\r\n"}, 2, StringSplitOptions.RemoveEmptyEntries) means that the whole string should be split into 2 parts only and since the string is processed from left to right, the split will occur on the first "\r\n" substring found.
I'm trying to split a string that can come in with either commas or newlines, based on an input from a textarea. I'm not sure of the syntax to split this string in c#.
Currently I have:
string[] splitString = inputString.Split(','); //WORKS
//string[] splitString = inputString.Split(new string[] { ",","\r\n","\n" }, StringSplitOptions.None); //DOES NOT WORK
Since some text uses \r for new line.
You should use the code below and remove the empty entries to make the array cleaner.
string[] splitString = inputString.Split(new string[] { ",", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);
or using Regex.Split. (This doesn't remove empty entries.)
String[] splitString = Regex.Split(inputString, "[,\r\n]");
Update
You can also use Regex.Split with empty entries removed, thanks to WiktorStribiżew's comment.
The code below removes the empty entries which aren't in the beginning or end of the string.
String[] splitString = Regex.Split(inputString, "[,\r\n]+");
To eliminate empty entries showing in the beginning or end of the line, use the code below.
Regex.Split(Regex.Replace(inputString, "^[,\r\n]+|[,\r\n]+$", ""), "[,\r\n]+");
Regular Expression Language
If you want more informations about Regex, or how it works, you can look here for a quick reference.
You can pass Environment.NewLine into your string array:
string[] splitString = inputString.Split(new string[] { ",", Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
I was wanting to split a string with a known delimiter between different parts into an array of strings using a method (e.g. MethodToSplitIntoArray(String toSplit) like in the example below. The values are string values which can have any character except for '{', '}', or ',' so am unable to delimit on any other character. The string can also contain undesired white space at the start and end as the file can be generated from multiple different sources, the desired information will also be inbetween "{" "}" and separated by a comma.
String valueCombined = " {value},{value1},{value2} ";
String[] values = MethodToSplitIntoArray(valueCombined);
foreach(String value in values)
{
//Do something with array
Label.Text += "\r\nString: " + value;
}
Where the label would show:
String: value
String: value1
String: value2
My current implementation of splitting method is below. It splits the values but includes any spaces before the first parenthesis and anything between them.
private String[] MethodToSplitIntoArray(String toSplit)
{
return filesPassed.Split(new string[] { "{", "}" }, StringSplitOptions.RemoveEmptyEntries);
}
I though this would separate out the strings between the curly braces and remove the rest of the string, but my output is:
String:
String: value
String: ,
String: value1
String: ,
String: value2
String:
What am I doing wrong in my split that I'm still getting the string values outside of the parenthesis? Ideally I would like to use regex or String.Split if its possible
For those with similar problems check out DotNet Perls on splitting
Making the assumption that commas are not permitted inside a curly brace pair, and that outside a curly brace pair only commas or whitespace will appear, it seems to me that the most straightforward, easy-to-read way to approach this is to first split on commas, then trim the results of that (to remove whitespace), and then finally to remove the first and last characters (which at that point should only be the curly braces):
valuesCombined.Split(',').Select(s => s.Trim().Substring(1, s.Length - 2)).ToArray();
I believe that including the curly braces in the initial split operation just makes everything harder, and is more likely to break in hard-to-identify ways (i.e. bad data will result in weirder results than if you use something like the above).
Add , to delimeters:
return filesPassed.Split(new char[] { '{', '}', ',' }, StringSplitOptions.RemoveEmptyEntries);
Not sure if you are expecting those spaces in the front and end so added some trimming to prevent empty results for those.
private String[] MethodToSplitIntoArray(String toSplit)
{
return toSplit.Trim().Split(new char[] { '{', '}', ',' }, StringSplitOptions.RemoveEmptyEntries);
}
This might be one of the way to get all the values as u are looking for
String valueCombined = " {value},{value1},{value2} ";
String[] values = valueCombined.Split(new string[] { "},{" }, StringSplitOptions.RemoveEmptyEntries);
int lastVal = values.Count() - 1;
values[0] = values[0].Replace("{", "");
values[lastVal] = values[lastVal].Replace("}", "");
What I did here is that splited the string with "},{" and then removed { from the first array item and } from the last array item.
Try regex and linq.
return Regex.Split(toSplit, "[.{.}.,]").Where(x => !string.IsNullOrWhiteSpace(x)).ToArray();
Though very late but can you try this:
Regex.Split(" { value},{ value1},{ value2};", #"\s*},{\s*|{\s*|},?;?").Where(s => string.IsNullOrWhiteSpace(s) == false).ToArray()
I have a string with the following text:
:0c4b7fcdffc38322555a9e35c22c9469:Nick:194176015020283762507:
How do I parse the final number? i.e.:
194176015020283762507
You should first use String.Split() to separate the string by the colon (':') separators. Then access the correct element.
var input = ":0c4b7fcdffc38322555a9e35c22c9469:Nick:194176015020283762507:";
var split = input.Split(':');
var final = split[3];
Note that by default, Split() keeps empty entries. You will have one at the beginning and end, because of the initial and ending colons. You could also use:
var split = input.Split(new[] {':'}, StringSplitOptions.RemoveEmptyEntries);
var final = split[2];
which, as the option implies, removes empty entries from the array. So your number would be at index 2 instead of 3.
string str = ":0c4b7fcdffc38322555a9e35c22c9469:Nick:194176015020283762507:";
string num = str.Split(':')[3];
var finalNumber = input.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries)
.Last()
This code will split your input string into strings, separated by : (empty strings are removed from start and end of sequence). And last string is returned, which is your finalNumber.
I have strings like this:
/Administration/References
/Administration/Menus/Home
etc
Is there an easy way that I can find the 1st, 2nd and 3rd words that appear in these strings and place it into an array. ie. the text between the slashes?
The easiest way in this case is
var words = myString.Split(new[]{'/'}, StringSplitOptions.RemoveEmptyEntries);
This will give you an array of all the words seperated by the slashes.
The StringSplitOptions.RemoveEmptyEntries will make sure that you don't get empty entries, since the string is starting with a / it will give an empty first element in the array. If you have a trailing / it will give a empty last element as well.
string.Split(new char[] { '/' })
See MSDN for more info:
http://msdn.microsoft.com/en-us/library/b873y76a.aspx
I think what you are looking for is the split method on string i.e.
string[] words = yourstring.Split('/');
It will give you a List that contains 1st line, 2nd line and etc. Each list item is an Array of strings that you want to parse.
private List<string[]> ParseText(string text)
{
string[] lines = text.Split(new string[] { System.Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
List<string[]> list = new List<string[]>();
foreach (var item in lines)
{
list.Add(item.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries));
}
return list;
}