Dennis Acker
Dennis Acker

Reputation: 3

Add regex string to array

I need to add a regex string to an array but I get an error like "string can't implement in string[]".

This is the code:

foreach (string ss in fileLines)
{
    filelinesclean = System.Text.RegularExpressions.Regex.Replace(ss, @"\s+", " ");
    MessageBox.Show("ok");
    System.IO.File.WriteAllLines(@"C:\Users\Public\WriteLines.txt", filelinesclean);
}

Upvotes: 0

Views: 89

Answers (2)

Mitesh
Mitesh

Reputation: 74

I am not sure about your requirement but it seems you are trying to use string in place of collection. This code may help.

List<string> lines = new List<string>();
foreach (string ss in fileLines)
{
   string filelinesclean = System.Text.RegularExpressions.Regex.Replace(ss, @"\s+", " ");
   lines.Add(filelinesclean);
}
System.IO.File.WriteAllLines(@"C:\Users\Public\WriteLines.txt", lines);

I have keep your code as it is and added/updated few lines.

Upvotes: 0

juharr
juharr

Reputation: 32266

First add the following usings so you don't need to type out the entire namespaces for everything.

using System.Text.RegularExpressions;
using System.IO;

The reason it doesn't work is because File.WriteAllLines expects a IEnumerabl<string> or a string[], but you're passing a string. Either use File.AppendAllText or just call File.WriteAllLines once after the foreach like this.

var lines = new List<string>();
foreach (string ss in fileLines)
{
    lines.Add(Regex.Replace(ss, @"\s+", " "));
}
MessageBox.Show("ok");
File.WriteAllLines(@"C:\Users\Public\WriteLines.txt", lines);

Or like this using Linq

File.WriteAllLines(
    @"C:\Users\Public\WriteLines.txt",
    fileLines.Select(ss => Regex.Replace(ss, @"\s+", " "));

But based on some of your comments you might want to do the following

File.WriteAllLines(
    @"C:\Users\Public\WriteLines.txt",
    File.ReadLines(@"InputPath")
        .Select(ss => Regex.Replace(ss, @"\s+", " "));

Because of lazy initialization that will read in each line of your input file one at a time, do the regular expression replacement then write the line out before moving to the next line. That will be scale-able if you need to run this on a very large file as it does not require the entire file to be in memory at one time.

Upvotes: 4

Related Questions