C# Regular expression To replace all matches in the string - c#

I Have one text file and I want to replaces all matches in each line, so I defined Pattern and I loop through to the text file after I want to write the result in another file, unfortunately my pattern is only replace first occurrence of the word what did |I do in a wrong way?
Content of text file:
"testebook kok o testebook\ntestbbb1232 joj ds testbbb1232"
using System.Text.RegularExpressions;
string filePath = "test.txt";
string fileNewPath = "test1.txt";
string ma = #"^test[0-9a-zA-Z]+";
string newString = string.Empty;
using(StreamReader sr = new(filePath)){
string line = sr.ReadLine();
while (line != null){
while(Regex.IsMatch(line, ma) != false){
line = Regex.Replace(line, ma, "");
}
newString += line + "\n";
line = sr.ReadLine();
}
}
using(StreamWriter sw = new(fileNewPath)){
sw.WriteLine(newString);
}

Your code is correct but your regex pattern is not correct.
you should write this:
string ma = #"test[0-9a-zA-Z]+";
The letter "^" has removed from pattern

So I modified My pattern and remove start with character and everything works now as desired
using System.Text.RegularExpressions;
string filePath = "test.txt";
string fileNewPath = "test1.txt";
MatchesFinder test = new(filePath, fileNewPath);
test.RunTheProcess();
class MatchesFinder{
private string filePath;
private string fileNewPath;
private string ma = #"test[a-zA-Z0-9]+";
public MatchesFinder(string filePath,string fileNewPath){
this.filePath = filePath;
this.fileNewPath = fileNewPath;
}
public void RunTheProcess(){
string newString = string.Empty;
using(StreamReader sr = new(filePath)){
string line = sr.ReadLine();
while (line != null){
while(Regex.IsMatch(line, ma) != false){
line = Regex.Replace(line, ma, string.Empty);
}
newString += line.TrimStart() + "\n";
line = sr.ReadLine();
}
}
using(StreamWriter sw = new(fileNewPath)){
sw.WriteLine(newString);
}
}
}

I think you don´t need to check IsMatch separately, just calling Regex.Replace should yield the same result.
Also, newString += line.TrimStart() + "\n"; means you´re copying all the lines you´ve already checked every time you append a new line. I´d either write directly to the output stream or at least use a StringBuilder if you really want to have the full file in memory for some reason.
Something like this:
using var sw = new StreamWriter(fileNewPath);
using var sr = new StreamReader(filePath);
var line = sr.ReadLine();
while (line != null){
line = Regex.Replace(line, ma, string.Empty);
sw.WriteLine(line.TrimStart());
line = sr.ReadLine();
}

Related

How to loop through the whole text file?

i need your help!, i am working on a script that, takes the string from a text file that grabs a value from the text file 20 characters.
Now i want to add spaces in front of character that was grabbed from the text file. However, i want to apply it to the whole text file.
For example:
Text 1 A (input):
01253654758965475896N12345
012536547589654758960011223325
(output):
(added 10 spaces in front)01253654758965475896 N12345
(added 10 spaces in front)01253654758965475896 0011223325
The idea is to loop through them, i added 10x spaces in front of and then also added spaces after 01253654758965475896.
Here is my code:
class Program
{
[STAThread]
static void Main(string[] args)
{
int acc = 1;
string calcted = (acc++).ToString().PadLeft(20, '0');
string ft_space = new string(' ', 12);
string path = Console.ReadLine();
using (StreamReader sr = File.OpenText(path))
{
string s = "";
while ((s = sr.ReadToEnd()) != null)
{
string px = s;
string cnd = s.Substring(0, 16);
string cdr = cnd;
px = ft_space + cdr;
Console.Write("Enter Location:");
string pt1 = Console.ReadLine();
if (!File.Exists(pt1))
{
using (TextWriter sw = File.CreateText(pt1))
{
sw.Write(px);
}
}
} Console.ReadKey();
}
}
}
}
As noted in the comments, first change ReadToEnd to ReadLine.
ReadToEnd will read all the file, ReadLine will read one line every loop iteration.
Then, since you want 20 characters and not 16, you need to change s.Substring(0, 16) to s.Substring(0, 20).
After that you need to obtain the rest of the line, so that will be s.Substring(20).
You then need to concatenate all the parts together like this:
string result = spaces10 + first_part + spaces3 + second_part;
Another problem is that you just write the first line since you check if the file exists every time on the loop and you don't write the line if the file exists.
Here is how your code will look after such changes (and others):
string spaces10 = new string(' ', 10);
string spaces3 = new string(' ', 3);
string input_file = Console.ReadLine();
Console.Write("Enter Location:");
string output_file = Console.ReadLine();
using (StreamReader sr = File.OpenText(input_file))
{
using (TextWriter sw = File.CreateText(output_file))
{
string line;
while ((line = sr.ReadLine()) != null)
{
string first_part = line.Substring(0, 20);
string second_part = line.Substring(20);
string result = spaces10 + first_part + spaces3 + second_part;
sw.WriteLine(result);
}
}
}
Console.ReadKey();

How can i delete space from text file and replace it semicolon?

I have this data into the test text file:
behzad razzaqi xezerlooot abrizii ast
i want delete space and replace space one semicolon character,write this code in c# for that:
string[] allLines = File.ReadAllLines(#"d:\test.txt");
using (StreamWriter sw = new StreamWriter(#"d:\test.txt"))
{
foreach (string line in allLines)
{
if (!string.IsNullOrEmpty(line) && line.Length > 1)
{
sw.WriteLine(line.Replace(" ", ";"));
}
}
}
MessageBox.Show("ok");
behzad;;razzaqi;;xezerlooot;;;abrizii;;;;;ast
but i want one semicolon in space.how can i solve that?
Regex is an option:
string[] allLines = File.ReadAllLines(#"d:\test.txt");
using (StreamWriter sw = new StreamWriter(#"d:\test.txt"))
{
foreach (string line in allLines)
{
if (!string.IsNullOrEmpty(line) && line.Length > 1)
{
sw.WriteLine(Regex.Replace(line,#"\s+",";"));
}
}
}
MessageBox.Show("ok");
Use this code:
string[] allLines = File.ReadAllLines(#"d:\test.txt");
using (StreamWriter sw = new StreamWriter(#"d:\test.txt"))
{
foreach (string line in allLines)
{
string[] words = line.Split(" ", StringSplitOptions.RemoveEmptyEntries);
string joined = String.Join(";", words);
sw.WriteLine(joined);
}
}
You need to use a regular expression:
(\s\s+)
Usage
var input = "behzad razzaqi xezerlooot abrizii ast";
var pattern = "(\s\s+)";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(input, ';');
You can do that with a regular expression.
using System.Text.RegularExpressions;
and:
string pattern = "\\s+";
string replacement = ";";
Regex rgx = new Regex(pattern);
sw.WriteLine(rgx.Replace(line, replacement));
This regular expression matches any series of 1 or more spaces and replaces the entire series with a semicolon.
you can try this
Regex r=new Regex(#"\s+");
string result=r.Replace("YourString",";");
\s+ is for matching all spaces. + is for one or more occurrences.
for more information on regular expression see http://www.w3schools.com/jsref/jsref_obj_regexp.asp
You should check a string length after replacement, not before ;-).
const string file = #"d:\test.txt";
var result = File.ReadAllLines(file).Select(line => Regex.Replace(line, #"\s+", ";"));
File.WriteAllLines(file, result.Where(line => line.Length > 1));
...and don't forget, that for input hello you will get ;hello;.

Read text file and split it over

So, I know my headline is a bit confusing, I will explain.
My code looks like this:
string filename = "C:\\C#\\maplist.txt"; // please put the text file path.
string filename2 = "C:\\C#\\zemaplist.txt";
string map;
StreamReader sr = new StreamReader(filename);
StreamWriter sw = new StreamWriter(filename2);
List<string> maps = new List<string> { };
while ((map = sr.ReadLine()) != null)
{
maps.Add(map);
}
sr.Close();
for (int i = 0; i < maps.Count; i++)
{
Console.WriteLine(maps[i]);
sw.WriteLine(maps[i]);
}
sw.Close();
and what i need to do is when the code read a new line, in my line there is
"Hey,Hey"
I want to split the , from each other so I can take both of them as other parameters, so that the first Hey will be added to maps and the other hey will be maps2,
How can I do that?
You can use Split() function to Split the given String based on delimiter.
Try This:
while ((map = sr.ReadLine()) != null)
{
maps.Add(map.Split(',')[0].Trim());
maps2.Add(map.Split(',')[1].Trim());
}
Simple Code:
using System.IO;
string filename = "C:\\C#\\maplist.txt"; // please put the text file path.
string filename2 = "C:\\C#\\zemaplist.txt";
string map;
StreamWriter sw = new StreamWriter(filename2);
List<string> maps = new List<string> { };
List<string> maps2 = new List<string> { };
String [] allLines = File.ReadAllLines(filename);
foreach(String line in allLines)
{
maps.Add(line.Split(',')[0].Trim());
maps2.Add(line.Split(',')[1].Trim());
}
for (int i = 0; i < maps.Count; i++)
{
Console.WriteLine(maps[i]);
sw.WriteLine(maps[i]);
}
sw.Close();
Solution 2:
String mapItem1="";
String mapItem2="";
if(maps.Count == maps2.Count)
{
for(int i=0;i<maps.Count;i++)
{
mapItem1=maps[i];
mapItem2=maps2[i];
}
}
while ((map = sr.ReadLine()) != null)
{
string[] split = map.Split(',');
//First Hey would be split[0], second Hey would be split[1]
maps.Add(split[0].Trim());
maps2.Add(split[1].Trim());
}
The Split method should help you out with that.
If you want to trim leading whitespace characters, you can use the .Trim() method on a string.
Use Split().
string heys = "Hey,Hey";
string[] splitArray = heys.Split(',');
Then you have:
splitArray[0] = "Hey";
splitArray[1] = "Hey";
Why even bother reading line by line? Read the entire file, replace the new line chars for a "," (to prevent last and first elements from different lines to be treated as one), and loop through a clean string.
string fileContent = Regex.Replace(File.ReadAllText("test.txt"), #"\r", ",");
List<string> mapList = new List<string>();
foreach (string map in Regex.Split(fileContent.Replace(#"\s+", ""), ","))
{
mapList.Add(map.Trim());
}

Detect space and add a comma

I have text file with employes email like this below
abc#ewr.com
xyc#df.co.nz
rte#pope.com
ssddsf#fdf.com
I want change to like this
abc#ewr.com, xyc#df.co.nz, rte#pope.com, ssddsf#fdf.com
How can i do using C# code?
string yourString = oldString.Replace(' ', ',');
Most likely it is not a space but a new line, so it would be
string yourString = oldString.Replace(Environment.NewLine, ",");
Could do this;
string linesFromFile = string.Empty;
// Read into string from file
using (StreamReader sr = new StreamReader("filename.txt"))
{
linesFromFile = sr.ReadToEnd();
linesFromFile = linesFromFile.Replace(Environment.NewLine, ",");
Console.WriteLine(linesFromFile);
}
// Write back from string to file
using (StreamWriter sw = new StreamWriter("newFilename.txt"))
{
foreach(string s in linesFromFile.Split(','))
{
sw.WriteLine(s);
}
}
this would replace CR\LF and spaces with ','
string newContent = string.Join(",",
File.ReadAllLines("sourceFile.txt")
).Replace(' ', ',')
File.WriteAllText("newFile.txt", newContent);
I'd operate on the file directly to avoid the overhead of reading a potentially huge employee database into a string:
private static void MungeFile(string filename)
{
FileStream fsOut = File.Create(filename+"_out");
FileStream fsIn = File.OpenRead(filename);
StreamReader sr = new StreamReader(fsIn);
StreamWriter sw = new StreamWriter(fsOut);
while (!sr.EndOfStream)
{
string inputLine = sr.ReadLine();
string terminator = (sr.EndOfStream ? "" : ",");
sw.Write(inputLine + terminator);
}
sw.Flush();
fsOut.Close();
}
Microsoft's documentation covers this one pretty well: http://msdn.microsoft.com/en-us/library/ms228599.aspx
Read in the text file as a string, then do something like this to replace the newlines with a comma (replace Environment.NewLine with ' ' if you are looking to replace spaces):
String newFile = oldFile.Replace(Environment.NewLine,',');

C#: How do I prepend text to each line in a string?

What would an implementation of 'MagicFunction' look like to make the following (nunit) test pass?
public MagicFunction_Should_Prepend_Given_String_To_Each_Line()
{
var str = #"line1
line2
line3";
var result = MagicFunction(str, "-- ");
var expected = #"-- line1
-- line2
-- line3";
Assert.AreEqual(expected, result);
}
string MagicFunction(string str, string prepend)
{
str = str.Replace("\n", "\n" + prepend);
str = prepend + str;
return str;
}
EDIT:
As others have pointed out, the newline characters vary between environments. If you're only planning to use this function on files that were created in the same environment then System.Environment will work fine. However, if you create a file on a Linux box and then transfer it over to a Windows box you'll want to specify a different type of newline. Since Linux uses \n and Windows uses \r\n this piece of code will work for both Windows and Linux files. If you're throwing Macs into the mix (\r) you'll have to come up with something a little more involved.
Use .Select on a list of the lines.
private static string MagicFunction(string str, string prefix)
{
string[] lines = str.Split(new[] { '\n' });
return string.Join("\n", lines.Select(s => prefix + s).ToArray());
}
How about:
string MagicFunction(string InputText) {
public static Regex regex = new Regex(
"(^|\\r\\n)",
RegexOptions.IgnoreCase
| RegexOptions.CultureInvariant
| RegexOptions.IgnorePatternWhitespace
| RegexOptions.Compiled
);
// This is the replacement string
public static string regexReplace =
"$1-- ";
// Replace the matched text in the InputText using the replacement pattern
string result = regex.Replace(InputText,regexReplace);
return result;
}
var result = "-- " + str.Replace(Environment.NewLine, Environment.NewLine + "-- ");
if you want it cope with either Windows (\r\n) NewLines or Unix ones (\n) then:
var result = "-- " + str.Replace("\n", "\n-- ");
No need to touch the \r as it is to be left where it was before. If however you want to cross between Unix and Windows then:
var result = "-- " + str.Replace("\r","").Replace("\n", Enviornment.NewLine + "-- ");
Will do it and return the result in the local OS's format
You could do it like that :
public string MagicFunction2(string str, string prefix)
{
bool first = true;
using(StringWriter writer = new StringWriter())
using(StringReader reader = new StringReader(str))
{
string line;
while((line = reader.ReadLine()) != null)
{
if (!first)
writer.WriteLine();
writer.Write(prefix + line);
first = false;
}
return writer.ToString();
}
}
You could split the string by Environment.NewLine, and then add the prefix to each of those string, and then join them by Environment.NewLine.
string MagicFunction(string prefix, string orignalString)
{
List<string> prefixed = new List<string>();
foreach (string s in orignalString.Split(new[]{Environment.NewLine}, StringSplitOptions.None))
{
prefixed.Add(prefix + s);
}
return String.Join(Environment.NewLine, prefixed.ToArray());
}
How about this. It uses StringBuilder in case you are planning on prepending a lot of lines.
string MagicFunction(string input)
{
StringBuilder sb = new StringBuilder();
StringReader sr = new StringReader(input);
string line = null;
using(StringReader sr = new StringReader(input))
{
while((line = sr.ReadLine()) != null)
{
sb.Append(String.Concat("-- ", line, System.Environment.NewLine));
}
}
return sb.ToString();
}
Thanks all for your answers. I implemented the MagicFunction as an extension method. It leverages Thomas Levesque's answer but is enhanced to handle all major environments AND assumes you want the output string to use the same newline terminator of the input string.
I favored Thomas Levesque's answer (over Spencer Ruport's, Fredrik Mork's, Lazarus, and JDunkerley) because it was the best performing. I'll post performance results on my blog and link here later for those interested.
(Obviously, the function name of 'MagicFunctionIO' should be changed. I went with 'PrependEachLineWith')
public static string MagicFunctionIO(this string self, string prefix)
{
string terminator = self.GetLineTerminator();
using (StringWriter writer = new StringWriter())
{
using (StringReader reader = new StringReader(self))
{
bool first = true;
string line;
while ((line = reader.ReadLine()) != null)
{
if (!first)
writer.Write(terminator);
writer.Write(prefix + line);
first = false;
}
return writer.ToString();
}
}
}
public static string GetLineTerminator(this string self)
{
if (self.Contains("\r\n")) // windows
return "\r\n";
else if (self.Contains("\n")) // unix
return "\n";
else if (self.Contains("\r")) // mac
return "\r";
else // default, unknown env or no line terminators
return Environment.NewLine;
}

Categories

Resources