Split string into elements of a string array [duplicate] - c#

This question already has answers here:
How can I split a string with a string delimiter? [duplicate]
(7 answers)
Closed 8 years ago.
I've got a string with the format of:
blockh->127.0.0.1 testlocal.de->127.0.0.1 testlocal2.com
Now I need to seperate the elements, best way would be a string array I think. I would need to get only these elements seperated:
127.0.0.5 somerandompage.de
127.0.0.1 anotherrandompage.com
How to split and filter the array to get only these elements?
Using the .Filter() Methode doesn't to the job.

You can use the string Split method:
var st = "blockh->127.0.0.1 testlocal.de->127.0.0.1 testlocal2.com";
var result = st.Split(new [] { "->" }, StringSplitOptions.None);
You can achieve the same with a Regex:
var result = Regex.Split(st, "->");
As a note from #Chris both of these will split the string into an array with 3 elements:
blockh
127.0.0.1 testlocal.de
127.0.0.1 testlocal2.com
In case you want to get rid of blockh, you can do a regex match using an IP address and domain regex:
var ip = new Regex(#"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b\s*(([\w][\w\-\.]*)\.)?([\w][\w\-]+)(\.([\w][\w\.]*))");
var result = ip.Matches(st).Cast<Match>()
.Select(m => m.Value)
.ToArray();
This will get only the two elements containing IP addresses.

You can use a string Split() method to do that.
var s = "testlocal->testlocal2";
var splitted = s.Split(new[] {"->"}, StringSplitOptions.RemoveEmptyEntries); //result splitted[0]=testlocal, splitted[1]=testlocal2

If the simpler versions for splitting a string don't work for you, you will likely be served best by defining a Regular Expression and extracting matches.
That is described in detail in this MSDN article: http://msdn.microsoft.com/en-us/library/ms228595.aspx
For more information on how Regular Expressions can look this page is very helpful: http://regexone.com/

Related

Split a file using specific word in C# [duplicate]

This question already has answers here:
How to tell a RegEx to be greedy on an 'Or' Expression
(2 answers)
Closed 2 years ago.
there is a file which i want to split
MSH|^~\&||||^asdasdasd|||asdasd|637226866166648574|637226866166648574|2.4
EVN|asd|20200416|20200416
PID|1|PW9074asdasd41|asd|PW907441|asdsad^wqe^wqeqwe||19700524|M
MSH|^~\&||||^qweqwewqe|||qwewqeqw|637226866166648574|637226866166648574|2.4
EVN|P03|20200416|20200416
PID|1|PW907441|PW907441|PW907441|Purvis^Walter^Rayshawn||19700524|M
I want to split it using MSH so that the result would be an array of string
array[0]=
"MSH|^~\&||||^asdasdasd|||asdasd|637226866166648574|637226866166648574|2.4
EVN|asd|20200416|20200416
PID|1|PW9074asdasd41|asd|PW907441|asdsad^wqe^wqeqwe||19700524|M";
array[1]=
"MSH|^~\&||||^asdasdasd|||asdasd|637226866166648574|637226866166648574|2.4
EVN|asd|20200416|20200416
PID|1|PW9074asdasd41|asd|PW907441|asdsad^wqe^wqeqwe||19700524|M";
What I have tried so far:
string[] sentences = Regex.Split(a, #"\W*((?i)MSH(?-i))\W*");
result:
array[0]="";
array[1]="MSH";
array[2]="asdasdasd|||asdasd|637226866166648574|637226866166648574|2.4
EVN|asd|20200416|20200416
PID|1|PW9074asdasd41|asd|PW907441|asdsad^wqe^wqeqwe||19700524|M";
array[3]="MSH";
array[4]="asdasdasd|||asdasd|637226866166648574|637226866166648574|2.4
EVN|asd|20200416|20200416
PID|1|PW9074asdasd41|asd|PW907441|asdsad^wqe^wqeqwe||19700524|M";
Or atleast it should not miss |^~\&||||^ after split in index 1 and 2
You can simply use the Split() function for this. Below generates an IEnumerable, which you can make an array using ToArray if you wanted to:
void Main()
{
string s = #"MSH|^~\&||||^asdasdasd|||asdasd|637226866166648574|637226866166648574|2.4
EVN|asd|20200416|20200416
PID|1|PW9074asdasd41|asd|PW907441|asdsad^wqe^wqeqwe||19700524|M
MSH|^~\&||||^qweqwewqe|||qwewqeqw|637226866166648574|637226866166648574|2.4
EVN|P03|20200416|20200416
PID|1|PW907441|PW907441|PW907441|Purvis^Walter^Rayshawn||19700524|M";
foreach (var element in s.Split(new string[] { "MSH" }, StringSplitOptions.RemoveEmptyEntries).Select(x => $"MSH{x}"))
{
Console.WriteLine(element);
}
}
If you want to split on MSH, Cetin Basoz is right. It will perfectly work doing that :
var sentences = a.Split(new String[] { "MSH" }, StringSplitOptions.RemoveEmptyEntries);
If you wanna be case insensitive, you can use that which is much simpler than the regex you used previously :
var sentences = Regex.Split(a, "MSH", RegexOptions.IgnoreCase);

Use C# RegEx to retrieve a list of matching strings found in a source string? [duplicate]

This question already has an answer here:
Simple and tested online regex containing regex delimiters does not work in C# code
(1 answer)
Closed 3 years ago.
I'm a RegEx novice, so I'm hoping someone out there can give me a hint.
I want to find a straightforward way (using RegEx?) to extract a list/array of values that match a pattern from a string.
If source string is "Hello #bob and #mark and #dave", I want to retrieve a list containing "#bob", "#mark" and "#dave" or, even better, "bob", "mark" and "dave" (without the # symbol).
So far, I have something like this (in C#):
string note = "Hello, #bob and #mark and #dave";
var r = new Regex(#"/(#)\w+/g");
var listOfFound = r.Match(note);
I'm hoping listOfFound will be an array or a List containing the three values.
I could do this with some clever string parsing, but it seems like this should be a piece of cake for RegEx, if I could only come up with the right pattern.
Thanks for any help!
Regexes in C# don't need delimiters and options must be supplied as the second argument to the constructor, but are not required in this case as you can get all your matches using Regex.Matches. Note that by using a lookbehind for the # ((?<=#)) we can avoid having the # in the match:
string note = "Hello, #bob and #mark and #dave";
Regex r = new Regex(#"(?<=#)\w+");
foreach (Match match in r.Matches(note))
Console.WriteLine("Found '{0}' at position {1}", match.Value, match.Index);
Output:
Found 'bob' at position 8
Found 'mark' at position 17
Found 'dave' at position 27
To get all the values into a list/array you could use something like:
string note = "Hello, #bob and #mark and #dave";
Regex r = new Regex(#"(?<=#)\w+");
// list of matches
List<String> Matches = new List<String>();
foreach (Match match in r.Matches(note))
Matches.Add(match.Value);
// array of matches
String[] listOfFound = Matches.ToArray();
You could do it without Regex, for example:
var listOfFound = note.Split().Where(word => word.StartsWith("#"));
Replace
var listOfFound = r.Match(note);
by
var listOfFound = r.Matches(note);

C# - Split string into an array of string using RegEx and create a dictionary<string,string> [duplicate]

This question already has answers here:
Splitting a string in C#
(4 answers)
Closed 7 years ago.
How can i create a RegEx that will split a string format just like below into an array of string?
The string should have key and value seperated with semicolon, if there is no ',' that seperate the key-value, it should not have pass the test RegEx.
The string will look like this:
var splitMe = "[Key1,Value1][Key2,Value2][Key3,Value3][Key4,Value4]";
var splitedArray = Regex.Split(/'RegEx Here'/);
//Output value should like this one ["Key1,Value1","Key2,Value2","Key3,Value3","Key4,Value4"]
//this value also will be the key and value of a Dictionary<string,string>
It would be simpler to use Regex.Matches chained with Linq to get the dictionary directly :
var input = "[Key1,Value1][Key2,Value2][Key3,Value3][Key4,Value4]";
var dictionary = Regex.Matches(input, #"\[(?<key>\w+),(?<value>\w+)\]")
.Cast<Match>()
.ToDictionary(x => x.Groups["key"].Value, x => x.Groups["value"].Value);
This would work for you, I would imagine:
\[(\w+,\w+)\]
Regex101
I'm not sure what data you might have in keys and values but perhaps the following would be more inclusive?
\[([^,]+?,[^,]+?)\]
If you want to use split still you can match what you need with this:
(\[|\]\[|\])

Extract part of the string [duplicate]

This question already has answers here:
How do I split a string by a multi-character delimiter in C#?
(10 answers)
Closed 7 years ago.
I have thousands of lines of string type data, and what I need is to extract the string after AS. For example this line:
CASE END AS NoHearing,
What I want would be NoHearing,
This line:
CASE 19083812 END AS NoRequset
What I need would be NoRequset
So far I have tried couple ways of doing it but no success. Can't use .split because AS is not Char type.
If this will be the only way that AS appears in the string:
noRequestString = myString.Substring(myString.IndexOf("AS") + 3);
Using Regex I extract all between the AS and a comma:
string data = #"
CASE END AS NoHearing,
CASE 19083812 END AS NoRequset
";
var items = Regex.Matches(data, #"(?:AS\s+)(?<AsWhat>[^\s,]+)")
.OfType<Match>()
.Select (mt => mt.Groups["AsWhat"])
.ToList();
Console.WriteLine (string.Join(" ", items)); // NoHearing NoRequset

How can I split a string with a string delimiter? [duplicate]

This question already has answers here:
How do I split a string by a multi-character delimiter in C#?
(10 answers)
Closed 4 years ago.
I have this string:
"My name is Marco and I'm from Italy"
I'd like to split it, with the delimiter being is Marco and, so I should get an array with
My name at [0] and
I'm from Italy at [1].
How can I do it with C#?
I tried with:
.Split("is Marco and")
But it wants only a single char.
string[] tokens = str.Split(new[] { "is Marco and" }, StringSplitOptions.None);
If you have a single character delimiter (like for instance ,), you can reduce that to (note the single quotes):
string[] tokens = str.Split(',');
.Split(new string[] { "is Marco and" }, StringSplitOptions.None)
Consider the spaces surronding "is Marco and". Do you want to include the spaces in your result, or do you want them removed? It's quite possible that you want to use " is Marco and " as separator...
You are splitting a string on a fairly complex sub string. I'd use regular expressions instead of String.Split. The later is more for tokenizing you text.
For example:
var rx = new System.Text.RegularExpressions.Regex("is Marco and");
var array = rx.Split("My name is Marco and I'm from Italy");
Try this function instead.
string source = "My name is Marco and I'm from Italy";
string[] stringSeparators = new string[] {"is Marco and"};
var result = source.Split(stringSeparators, StringSplitOptions.None);
You could use the IndexOf method to get a location of the string, and split it using that position, and the length of the search string.
You can also use regular expression. A simple google search turned out with this
using System;
using System.Text.RegularExpressions;
class Program {
static void Main() {
string value = "cat\r\ndog\r\nanimal\r\nperson";
// Split the string on line breaks.
// ... The return value from Split is a string[] array.
string[] lines = Regex.Split(value, "\r\n");
foreach (string line in lines) {
Console.WriteLine(line);
}
}
}
Read C# Split String Examples - Dot Net Pearls and the solution can be something like:
var results = yourString.Split(new string[] { "is Marco and" }, StringSplitOptions.None);
There is a version of string.Split that takes an array of strings and a StringSplitOptions parameter:
http://msdn.microsoft.com/en-us/library/tabh47cf.aspx

Categories