I have a string variable like:
string data= "#FirstName=Arvind #LastName= Chaudhary_009"
Using Regex in C# i Want the output like :
FirstName = Arvind;
LastName= Chaudhary009;
There would be more ways of doing this. Two of them would be
string data = "#FirstName=Arvind #LastName= Chaudhary_009";
data = data.Replace("_", "");
data = data.Replace("=", " = ");
string[] dt = data.Split(new char[] {'#'}, StringSplitOptions.RemoveEmptyEntries);
Console.WriteLine(dt[0]); // Print your array here
Regex: Which you asked for
Regex regex = new Regex(#"#");
string[] dt1 = regex.Split(data).Where(s => s != String.Empty).ToArray();
Console.WriteLine(dt1[0]); // Print your array here
You can print array the way you want
Edit
After Understanding the requirements from comments
string data = "#FirstName=Arvind #LastName= Chaudhary_009";
data = data.Replace("_", "");
string[] dt = data.Split(new char[] {'#'}, StringSplitOptions.RemoveEmptyEntries);
Regex regex = new Regex(#"#");
string[] dt1 = regex.Split(data).Where(s => s != String.Empty).ToArray();
foreach(string d in dt)
{
//this will print both the line
Console.WriteLine(d);
}
foreach(string d in dt1)
{
//this will print both the line
Console.WriteLine(d);
}
There will be many solutions. I suggest you use .NET Regex Tester or a similar online tool to help develop a regex that works well.
A simple example regex that will give you some groups:
#FirstName\s*=\s*(.*)\s?#LastName\s*=\s*(.*)_(.*)
Run that and then format up the output based on groups 1, 2, 3.
Related
I have this string, I want to get the part after the date. The part till date always remains the same. I would have hoped to get the index of date but it changes always hence I can't use it.
var str = "c:\ somefolder\ download\ 2019-14-11 merchandise of today"
char[] spearator = {" "};
var _split = str.Split(spearator);
Here I have all the words broken down according to spaces.
How do I get the 'merchandise of today'?
You can try following codes, use the regular expression
var str = #"c:\ somefolder\ download\ 2019-14-11 merchandise of today";
var reg = new Regex(#".+\d{4}-\d{2}-\d{2}");
var result = reg.Replace(str, string.Empty).Trim();
If the format of the date does not change, you could do the following:
var path = #"C:\Example\Download\2019-14-11 Merchandise Of Today";
var merchandise = path.Substring(path.LastIndexOf('\\')).Trim();
OR
var merchandiseWithoutDate = path.Substring(path.IndexOf(' ').Trim();
That will output the date and merchandise of today, if you change the character to a space you will also retrieve that.
What Substring is basically allows you to control an index to begin and end, which allows you to mitigate the text received.
//Thanks guys!
//This is what I did before I saw the two answers. I know it is messy a lot and now I am //gonna try the substring method but this was a temporary fix for me. Thanks again!
var str = "c:\ somefolder\ download\ 2019-14-11 merchandise of today"
char[] spearator = {" "};
var _split = str.Split(spearator);
int len = _split.lenght-1;
for(i=0; i<_split.lenght; i++)
{
var getStr = _split[i]
Match search = regex.match(getStr, "my regex patern for date");
if (search.success)
{
var converted = search.tostring();
int index = Array.IndexOf(_split, converted)
index++;
string temp = "";
while(index<=len_)
{
string temp = temp+ " "+_split[index];
index++;
}
console.writeline("String is {0}", temp);
}
}
This question already exists:
C# split string but keep split chars / separators [duplicate]
Closed 4 years ago.
Is there a clever way to do the following string manipulation in C#?
I have any kind of string and im looking for a specified delimiter. The code should divide the string in words before and after delimiter and also include the delimiter. The delimiter could be several times in a row and also could be in the start or the end.
// PSEUDO CODE
string = "Hello****wide****world";
delimiter = "****";
// result should be a list<string> like
{"Hello","****","wide","****","world"}
You can try to use Regex and the pattern is (\*{4}).
string data = "Hello****wide****world";
string[] words = Regex.Split(data, #"(\*{4})");
List<string> result = words.ToList();
NOTE
* is a keyword in regex string, so you need to use \ to escape it.
c# online
i'll say split the string with the delimiter, then when creating the result add the delimiter after each item in the array.
string fullWord = "Hello****wide****world";
string delimiter = "****";
var listOfWords = fullWord.Split(delimiter);
List<string> result = new List<string>();
foreach(var item in listOfWords){
result.Add(item);
result.Add(delimiter);
}
return result;
You can do it like this. In the end, you can iterate over the result.
string input = "Hello****wide****world";
string delimiter = "****";
var listOfWords = input.Split(new string[] { delimiter }, StringSplitOptions.None);
List<string> result = new List<string>();
foreach (var item in listOfWords)
{
if (!item.Equals(listOfWords.Last()))
{
result.Add(item);
result.Add(delimiter);
}
else
{
result.Add(item);
}
}
untested
string[] words = Regex.Split(originalString, #"(?=****)");
List<string> wordsLst = words.ToList();
User Regex to do it :
string input = "Hello****wide****world";
string pattern = "(****)";
string[] substrings = Regex.Split(input, pattern);
string fullWord = "Hello****wide****world";
string delimiter = "****";
var listOfWords = fullWord.Split(delimiter);
StringBuilder result = new StringBuilder("");
result.Append("{");
foreach(var item in listOfWords){
if (!item.Equals(listOfWords.Last()))
{
result.Append($"\"{item}\",\"{delimiter}\",");
}
else
{
result.Append($"\"{item}\"");
}
}
result.Append("}");
var stringResult=result.ToString();
My Question consists of how might i split a string like this:
""List of devices attached\r\n9887bc314\tdevice\r\n12n1n2nj1jn2
\tdevice\r\n\r\n"
Into:
[n9887bc314,n12n1n2nj1jn2]
I have tried this but it throws the error "Argument 1: cannot convert from 'string' to 'char'"
string[] delimiterChars = new string[] {"\\","r","n","tdevice"};
string y = output.Substring(z+1);
string[] words;
words = y.Split(delimiterChars, StringSplitOptions.None);
I'm wondering if i'm doing something wrong because i'm quite new at c#.
Thanks A Lot
First of all String.Split accept strings[] as delimiters
Here is my code, hope it will helps:
string input = "List of devices attached\r\n9887bc314\tdevice\r\n12n1n2nj1jn2\tdevice\r\n\r\n";
string[] delimiterChars = {
"\r\n",
"\tdevice",
"List of devices attached"
};
var words = input.Split(delimiterChars, StringSplitOptions.RemoveEmptyEntries);
foreach (var word in words)
{
Console.WriteLine(word);
}
Split the whole string by the word device and then remove the tabs and new lines from them. Here is how:
var wholeString = "List of devices attached\r\n9887bc314\tdevice\r\n12n1n2nj1jn2\tdevice\r\n\r\n";
var splits = wholeString.Split(new[] { "device" }, StringSplitOptions.RemoveEmptyEntries);
var device1 = splits[1].Substring(splits[1].IndexOf("\n") + 1).Replace("\t", "");
var device2 = splits[2].Substring(splits[2].IndexOf("\n") + 1).Replace("\t", "");
I've been doing a first aproach and it works, it might help:
I splited the input looking for "/tdevice" and then cleaned everyting before /r/n including the /r/n itself. It did the job and should work with your adb output.
EDIT:
I've refactored my answer to consider #LANimal answer (split using all delimiters) and I tried this code and works. (note the # usage)
static void Main(string[] args)
{
var inputString = #"List of devices attached\r\n9887bc314\tdevice\r\n12n1n2nj1jn2\tdevice\r\n\r\n";
string[] delimiters = {
#"\r\n",
#"\tdevice",
#"List of devices attached"
};
var chunks = inputString.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
string result = "[";
for (int i = 0; i < chunks.Length; i++)
{
result += chunks[i] + ",";
}
result = result.Remove(result.Length - 1);
result += "]";
Console.WriteLine(result);
Console.ReadLine();
}
I hope it helps,
Juan
You could do:
string str = #"List of devices attached\r\n9887bc314\tdevice\r\n12n1n2nj1jn2\tdevice\r\n\r\n";
string[] lines = str.Split(new[] { #"\r\n" }, StringSplitOptions.None);
string firstDevice = lines[1].Replace(#"\tdevice", "");
string secondDevice = lines[2].Replace(#"\tdevice", "");
I have a text file with the following information:
ALLOC
apple1
orange1
banana1
ALLOC
apple2
orange2
banana2
ALLOC
apple3
orange3
banana3
Based on the help from stackflow community, I am now able to read the whole file.I also found out that to extract contents between a tag, for ex, ALLOC, I could write:
var filelocation = #"c:\Fruits.txt";
var sectionLines = File.ReadAllLines(filelocation).TakeWhile(l => !l.StartsWith("ALLOC"));
But this will give me IEnumerable<string>:
apple1
orange1
banana1
apple2
orange2
banana2
apple3
orange3
How do I create 3 separate strings as
string1 = apple1 orange1 banana1
string2 = apple2 ornage2 banana2
string3 = apple3 orange3
In short, need to extract contents between tags.
Here is some approach how you can return result which you want:
string[] words = { "ALLOC", "apple1", "orange1", "banana1", "ALLOC", "apple2", "orange2", "banana2", "ALLOC" };
var result = string.Join(" ", words)
.Split(new string[] { "ALLOC" }, StringSplitOptions.RemoveEmptyEntries)
.Select(p => p.Trim(' '));
First I am making single string of all words. Than I am splitting by "ALLOC", and selecting trimmed strings.
Result is:
string[] result = { "apple1 orange1 banana1", "apple2 orange2 banana2" };
For your case,
var filelocation = #"c:\Fruits.txt";
var allLines = File.ReadAllLines(filelocation);
var sectionLines = string.Join(" ", allLines)
.Split(new string[] { "ALLOC" }, StringSplitOptions.RemoveEmptyEntries)
.Select(p => p.Trim(' '));
This might do the trick for you
string fullstr = File.ReadAllText("c:\\Fruits.txt");
string[] parts = fullstr.Split(new string[] { "ALLOC" }, StringSplitOptions.RemoveEmptyEntries);
List<string> outputstr = new List<string>();
foreach(string p in parts)
{
outputstr.Add(p.Replace("\r\n", " ").Trim(' '));
}
Here we read all text at once using File.ReadAllText and then splitted it with ALLOC and then in the outputstr just added the splitted string by replacing \r\n that is new line with a space and trimmed the result.
if i have a string like
string hello="HelloworldHellofriendsHelloPeople";
i would like to store this in a string like this
Helloworld
Hellofriends
HelloPeople
It has to change the line when it finds the string "hello"
thanks
string hello = "HelloworldHellofriendsHelloPeople";
var a = hello.Split(new string[] { "Hello"}, StringSplitOptions.RemoveEmptyEntries);
foreach (string s in a)
Console.WriteLine("Hello" + s);
var result = hello.Split(new[] { "Hello" },
StringSplitOptions.RemoveEmptyEntries)
.Select(s => "Hello" + s);
You can use this regex
(?=Hello)
and then split the string using regex's split method!
Your code would be:
String matchpattern = #"(?=Hello)";
Regex re = new Regex(matchpattern);
String[] splitarray = re.Split(sourcestring);
You can use this code - based on string.Replace
var replace = hello.Replace( "Hello", "-Hello" );
var result = replace.Split("-");
You could use string.split to split on the word "Hello", and then append "Hello" back onto the string.
string[] helloArray = string.split("Hello");
foreach(string hello in helloArray)
{
hello = "Hello" + hello;
}
That will give the output you want of
Helloworld
Hellofriends
HelloPeople