C# Regex quick help
I'm trying to read a text file, and then break it up by each line thats is split by a "\n". Then Regex it and write out the re开发者_运维技巧gex.
string contents = File.ReadAllText(filename);
string[] firefox = filename.Split("\r\n");
string prefix = prefix = Regex.Match(firefox, @"(\d)").Groups[0].Value;
File.AppendAllText(workingdirform2 + "configuration.txt", prefix);
string[] firefox = filename.Split("\r\n"); doesnt exactly work.
What I want to do is run a regex foreach line of contents and then write out each line after the regex
So...
filename:
Hero123 Hero243 Hero5959writes out to:
13 243 5959Well everybody is suggesting something off the base in which i started. the ending result will be about a 20 line regex with Ints. I've got to parse it out line by line.
File.ReadAllLines
var lines = File.ReadAllLines(originalPath);
File.WriteAllLines(newPath, lines
.Select(l => Regex.Match(l, @"\d+").Value).ToArray());
There are a number of problems with your code:
The reason the splitting doesn't work, is because you're splitting filename
, not contents
, which contains the actual file data. I agree with the other poster on using File.ReadAllLines :) It's a little more flexible with the file format compared to using \r\n
, amongst other things.
Also, you have string prefix = prefix = ...
, the second equals sign is probably intended to be a +
. You should using StringBuilder if the data files can become large, or better yet, write to an output stream as you go.
Passing an array to Regex.Match
doesn't work either. To apply the regex to all lines, you should do something like:
foreach (string line in firefox)
{
prefix = prefix + Regex.Match(line, // etc
// Or rather:
// stringBuilder.AppendLine(...)
}
Either that, or do it all at once with a multiline regex :)
精彩评论