Advertisement
Tician

Regex, C#, data processing

Sep 30th, 2016
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.15 KB | None | 0 0
  1. /*Heya! Would like to store some stuff I learned lately.
  2. Regex is short for Regular Expression and I would call it a very powerful search-routine. Like normally when you search for a file that starts with "ABC" you would search for "ABC*.*" or maybe just "ABC*" right? But what when you want a File that starts with "ABC", has "LMN" in the middle but doesn't have any "I, J and K" in the whole name? This is what Regex is for, much more powerful but tbh it looks pretty complex first (to be exact it looks like someone just facerolled over the keyboard), but I would say you can find ANYTHING in any text or any file in thousands of files.
  3. A very wonderful site I discovered is this one: https://regex101.com/
  4. Feel free to try out whatever you like, it even will explain what the different parts mean as soon as you enter something.*/
  5.  
  6. //now let's get serious, to be able to use Regex you have to add a using-reference
  7. using System.Text.RegularExpressions;
  8. //and for working with files and texts we need Input/Output
  9. using System.IO;
  10.  
  11. //to get all text in a file
  12. string allText = File.ReadAllText("C:\\Temp\\example.txt");
  13. /*now I just placed the searching routine here: for a line that includes "PathToPDF=" and the search result (reg1) is everything that comes after that. But it doesn't search anything yet.*/
  14. Regex reg1 = new Regex("(?<=SaySomething\\=).+");
  15. /*Careful, Regex needs the "\" to literally get the "=" but C# needs another "\" to be able to literally get the "\" for the "=". How confusing. Regex only would be like this: (?<=SaySomething\=).+        */
  16. //Let's search!
  17. Match something = reg1.Match(allText);
  18. //You will notice fast you can't do much with the Match - but it has our result we need that!
  19. string stringSomething = Convert.ToString(something);
  20.  
  21. /*OK what did I do? Let's say in our file we had a line like this:
  22. blabla SaySomething=Hello!
  23. Our search-result which is now stored in the stringpdfPath-variable is "Hello!"
  24.  
  25. The code to replace "Hello!" with "Good bye!" (and yes it keeps everything else in the file) is this:*/
  26. text2 = text2.Replace("SaySomething="+stringSomething, "SaySomething=Good bye!");
  27. File.WriteAllText("example.txt", text2);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement