hi and thanks for Reading . I have problems with Foreach loops.
from what I can see that foreach output is done one time for all phases.
here is an example of my problem.
string[] substrings = Regex.Split(Input, splitPattern);
foreach (string match in substrings)
{
Console.WriteLine("'{0}'" , match + "this is first match ") ;
}
output is :
match 1
match 2
match 3
this is first match
Questions 1 my problem is that the word " this is first match " display after all matchs, not after each match. I would like to maniplate each match alone. Because rather the writeline, I am going to assign the values of each match to an object, so if I have 5 matchs that mean 5 objects.
Question 2 : How to treat each match separated (with or without foreach loop).
thanks
If you need to use Regex.Split
, you need to define a pattern (I see you are using a fake one xxx
), then use the Regex.Split
, and note that this function is likely to return empty values between consecutive delimiters and at the beginning of the string. This pruning can be done with some LINQ: .Where(p => !string.IsNullOrWhiteSpace(p))
. This Where
will iterate through all the elements in the IEnumarable collection, and check if the elements are null or just whitespace. If the element is null or whitespace only, it will be discarded from the result. .ToList()
will convert the IEnumerable into a string list (List<string>
).
Thus, after running Regex.Split
, prune the result from the empty strings.
The @""
is a verbatim string literal. Inside it, all backslashes (and escape sequences) are treated as literals (@"\n"
is a string containing 2 characters, \
and n
, not a newline symbol). It is very convenient to write @"\s+"
to match 1 or more whitespace than "\\s+"
.
using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
public class Test
{
public static void Main()
{
var line = "xxx abcdef abcdef xxx zxcvbn zxcvbn xxx poiuy poiuy";
var splts = Regex.Split(line, @"xxx").Where(p => !string.IsNullOrWhiteSpace(p)).ToList();
//Console.WriteLine(splts.Count()); // => 3
foreach (string match in splts)
{
Console.WriteLine("'{0}'" , match);
}
}
Output:
' abcdef abcdef '
' zxcvbn zxcvbn '
' poiuy poiuy'