Find Specific String in Richtextbox C# - c#

Hello I need to find a word in my Richtextbox I need to find the string "ERP Points and ERP Bonus Point"
Here's the contents of a Richboxtext:
https://pastebin.com/vdPQx5E4
Now here's my code:
string resultString = "";
foreach (string line in richTextBox2.Lines)
{
if (line.Contains("ERP Points") || line.Contains("ERP Bonus Point"))
{
resultString = richTextBox2.GetLineFromCharIndex(richTextBox2.Find("ERP", RichTextBoxFinds.MatchCase)).ToString();
var result = Regex.Replace(line, #"\D", "");
string output = Regex.Replace(line, "[^0-9]+", string.Empty);
MessageBox.Show(resultString);
MessageBox.Show(output);
FontArial = 1;
FontSize = Int32.Parse(output);
}
else
{
FontArial = 0;
FontSize = 0;
}
}
and here's my another version which gives me 153 and I don't know where the program gets that:
resultString = richTextBox2.GetLineFromCharIndex(richTextBox2.Find("ERP", RichTextBoxFinds.None)).ToString();
var result = Regex.Replace(line, #"\D", "");
string output = Regex.Replace(resultString, "[^0-9]+", string.Empty);
MessageBox.Show(resultString.ToString());
MessageBox.Show(output);
if (output != "")
{
FontArial = 1;
FontSize = Int32.Parse(output);
}
else
{
FontArial = 0;
FontSize = 0;
}

Related

Opening a file and using the string within

When I open a file (I made myself) I need to use somethings out of the string of text that comes trough. I want to use some parts of the text as coordinates to draw a graph with.
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
char XgetalEen;
char XgetalTwee;
char YgetalEen;
char Ygetaltwee;
string XgetalSamen = "";
string YgetalSamen = "";
int coordinaatX;
int coordinaatY;
DialogResult lel = MessageBox.Show("Do you want to close this file?", "OPEN", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (lel == DialogResult.Yes)
{
Open();
foreach(string s in Gcowde)
{
XgetalEen = s[5];
XgetalTwee = s[6];
YgetalEen = s[8];
Ygetaltwee = s[9];
XgetalSamen += XgetalEen + XgetalTwee;
YgetalSamen += YgetalEen + Ygetaltwee;
if(XgetalTwee==' ')
{
XgetalSamen = "";
XgetalTwee = '0';
XgetalSamen += XgetalTwee + XgetalEen;
YgetalEen = s[7];
Ygetaltwee = s[8];
YgetalSamen = "";
YgetalSamen += YgetalEen + Ygetaltwee;
}
if(Ygetaltwee==' ')
{
Ygetaltwee = '0';
YgetalSamen = "";
YgetalSamen += Ygetaltwee + YgetalEen;
}
MessageBox.Show(XgetalSamen + " " + YgetalSamen);
Int32.TryParse(XgetalSamen, out coordinaatX);
Int32.TryParse(YgetalSamen, out coordinaatY);
currentLocation.X += coordinaatX;
currentLocation.Y += coordinaatY;
Coord.Add(new Point(currentLocation.X, currentLocation.Y));
}
drawerryting();
}
}
public void Open()
{
Gcowde.Clear();
listBox1.Items.Clear();
Coord.Clear();
werkVlak.Clear(Color.Black);
Coord.Add(new Point(pictureBox1.Width / 2, pictureBox1.Height / 2));
drawerryting();
OpenFileDialog openFileDialog1 = new OpenFileDialog();
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
StreamReader sr = new StreamReader(openFileDialog1.FileName);
string errything = sr.ReadToEnd();
string charAdded = "";
foreach (char s in errything)
{
if (s == '\n')
{
Gcowde.Add(charAdded);
charAdded = "";
}
else
{
charAdded += s;
}
}
foreach (string s in Gcowde)
{
listBox1.Items.Add(s);
}
sr.Close();
}
This is the code how I open the file and get the coordinates out of the string. The string is of this kind L1 G2 X50 Y50. i need to get the 2 50s out of the string.
ps.: the variables are in dutch.
XgetalEen = XnumberOne, XgetalTwee=XnumberTwo,
same goes for Y.
XgetalSamen=XnumberTogether, YgetalSamen=YnumberTogether.
This is a simple example how you could parse the file:
// Read your file using File.ReadAllLines
String[] lines = new[] { "L1 G2 X50 Y50", "L1 G2 X50 Y50" };
foreach (var line in lines)
{
String[] values = line.Split(' ');
string x = values.Where(s => s.StartsWith("X")).First().Replace("X", String.Empty);
int xCoordinate = Convert.ToInt32(x);
}
Don't forget to add all necessary checks and reading of other variables.

Change date format in a txt/csv file with , separator

I have a lot of .txt files with data in it. The data is separated with a ,.
In the third column the data is in the dd-mm-yyyy format. But it has to be in yyyy/mm/dd format. Changing the machine format isn't a solution.
The files are small enough to load into memory and opened on the following way, but I can't figured out how to solve the date issue. Who can help me?
foreach (string x in a)
{
string somePath = #"C:\test\";
string filename = x;
string path = Path.Combine(somePath, filename);
string str = File.ReadAllText(path);
str = str.Replace("AS", "");
File.WriteAllText(path, str);
}
Here's a quick example using ReadAllLines() and WriteAllLines():
string[] lines;
string somePath = #"C:\test\";
foreach (string x in a)
{
string path = Path.Combine(somePath, x);
lines = File.ReadAllLines(path);
for (int i = 0; i < lines.Length;i++)
{
lines[i] = lines[i].Replace("AS", "");
string[] values = lines[i].Split(',');
if (values.Length >= 3)
{
string[] parts = values[2].Split('-');
if (parts.Length == 3)
{
values[2] = String.Format("{0}/{1}/{2}", parts[2], parts[1], parts[0]);
lines[i] = String.Join(",", values);
}
}
}
File.WriteAllLines(path, lines);
}
Just loop through all the lines, split the string, try to parse it, then write it in the correct format to the output file.
foreach (string x in a)
{
string somePath = #"C:\test\";
string filename = x;
string path = Path.Combine(somePath, filename);
string str = File.ReadAllText(path);
str = str.Replace("AS", "");
var lines = str.Split('\n');
foreach(var line in lines)
{
var parts = line.Split(',');
if(parts.Length > 2)
{
var d = parts[2];
DateTime dateValue;
if (DateTime.TryParseExact(d, "dd-MM-yyyy", new CultureInfo("en-US"),
DateTimeStyles.None, out dateValue))
{
var dateTxt = dateValue.ToString("yyyy/mm/dd");
...etc...
}
}
}
File.WriteAllText(path, str);
}

Unexpected "," from StreamReader to StreamWriter

I've tried a lot of things as well as research and asking friends, but can't seem to write a second line without a "," replacing the line. All I'd to do is have a single line for each item read in a separate file.
Each read file has several of these items:
2/20/2014 7:33:10 AM
OPERATOR: jason
FILE: C:\ax14\Setups\000062363106RH.prt
UNITS: english
TEST RESULT: Pass
CHANNEL 1
TEST TYPE: VELOCITY
RESULT: Pass
UPPER LIMIT: 0.2260
LOWER LIMIT: 0.2220
MAX THICKNESS: 2.0110
MIN THICKNESS: 1.0110
MEASURED VELOCITY: 0.2225
MEASURED THICKNESS: 1.5215
Id like to have the date and velocity line in one line like this:
"2/20/2014 7:33:10 AM, MEASURED VELOCITY: 0.2225"
and this is my problem
2/20/2014 7:33:10 AM,
,
,
,
,
,
,
,
,
,
,
,
, MEASURED VELOCITY: 0.2225
,
2/20/2014 7:52:28 AM,
,
,
,
,
,
,
,
,
,
,
,
, MEASURED VELOCITY: 0.2224
,
2/20/2014 7:58:46 AM,
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Collections;
namespace conApp
{
class Program
{
static void Main(string[] args)
{
String line;
try
{
using (StreamWriter sw = new StreamWriter("C:\\writetest\\writetest.txt"))
{
string mydirpath = "C:\\chat\\";
string[] txtFileList = Directory.GetFiles(mydirpath, "*.txt");
foreach (string txtName in txtFileList)
{
System.IO.StreamReader sr = new System.IO.StreamReader(txtName);
while ((line = sr.ReadLine()) != null)
{
if (!string.IsNullOrEmpty(line))
{
String spart = ".prt";
String sam = " AM";
String spm = " PM";
String sresult = "TEST RESULT: ";
String svelocity = "MEASURED VELOCITY: ";
String part = "";
String date = "";
String result = "";
String velocity = "";
// sw.WriteLine(line);
if (line.Contains(sam))
{
date = line;
}
if (line.Contains(spm))
{
date = line;
}
if (line.Contains(spart))
{
part = line;
}
if (line.Contains(sresult))
{
result = line;
}
if (line.Contains(svelocity))
{
velocity = line;
}
int I = 2;
string[] x = new string[I];
x[0] = date;
x[1] = velocity;
sw.WriteLine(x[0] + "," + x[1]);
}
}
}
}
}
catch
{
}
}
}
}
Here is my suggestion for the full Main() trying to use as much from your code as possible. Declaring your vars outside the while statement you don't need to make it null.
EDIT- I forgot you said:
Each read file has several of these items
So added a few lines to handle that.
static void Main(string[] args)
{
string line;
try
{
using (StreamWriter sw = new StreamWriter("C:\\writetest\\writetest.txt"))
{
string mydirpath = "C:\\chat\\";
string[] txtFileList = Directory.GetFiles(mydirpath, "*.txt");
foreach (string txtName in txtFileList)
{
string spart = ".prt";
string sam = " AM";
string spm = " PM";
string sresult = "TEST RESULT: ";
string svelocity = "MEASURED VELOCITY: ";
string part = string.Empty;
string date = string.Empty;
string result = string.Empty;
string velocity = string.Empty;
using (StreamReader sr = new StreamReader(txtName))
{
while ((line = sr.ReadLine()) != null)
{
if (!string.IsNullOrEmpty(line) && line.Trim().Length != 0)
{
if (line.Contains(sam) || line.Contains(spm))
{
// Every new date means a new record. If you already have data for a record, first write it.
if (date != string.Empty && velocity != string.Empty)
{
int I = 2;
string[] x = new string[I];
x[0] = date;
x[1] = velocity;
sw.WriteLine(x[0] + "," + x[1]);
}
// Then reset data to prepare it for a new record
part = string.Empty;
result = string.Empty;
velocity = string.Empty;
date = line;
}
if (line.Contains(spart))
{
part = line;
}
if (line.Contains(sresult))
{
result = line;
}
if (line.Contains(svelocity))
{
velocity = line;
}
}
}
}
// After last record you still have some data to write
if (date != string.Empty && velocity != string.Empty)
{
int I = 2;
string[] x = new string[I];
x[0] = date;
x[1] = velocity;
sw.WriteLine(x[0] + "," + x[1]);
}
}
}
}
catch
{
}
}
Only write the line once you have both values:
Then reset both values to null.
sw.WriteLine(x[0] + "," + x[1]);
Becomes:
if ( !String.IsNullOrWhitespace( date) && !String.IsNullOrWhitespace( velocity )
{
sw.WriteLine(x[0] + "," + x[1]);
date = null;
velocity = null;
}
As Blas mentioned you also need to move the variables outside the while statement:
String result = "";
String velocity = "";
while ((line = sr.ReadLine()) != null)
You can use this Regex Pattern to Achieve your goal :
(^.*?(?:AM|PM).*?)\r?\n.*(MEASURED VELOCITY:.*?$).*
And here's the code:
using (StreamWriter sw = new StreamWriter("C:\\writetest\\writetest.txt"))
{
string mydirpath = "C:\\chat\\";
string[] txtFileList = Directory.GetFiles(mydirpath, "*.txt");
Regex regex = new Regex("(^.*?(?:AM|PM).*?)\r?\n.*(MEASURED VELOCITY:.*?$).*",
RegexOptions.Multiline | RegexOptions.Singleline);
foreach (string txtName in txtFileList)
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(txtName))
{
string text = sr.ReadToEnd();
sw.WriteLine(regex.Replace(text, "$1, $2"));
}
}
}
Output for given file example:
2/20/2014 7:33:10 AM, MEASURED VELOCITY: 0.2225

alchemy api in c# for text extractor

I want to extract text from web page at a run time then, use alchemy api in asp.net with c# but I don't know how to use this api in c#. I am trying to find out what the parameter of text extractor is. If needed I can also try to regular expression for extracting the web page but this was not clean html tags.
private void Form3_Load(object sender, EventArgs e)
{
}
void GetPosition(Uri url, string searchTerm)
{
string raw = "http://www.google.co.in/search?num=39&q={0}&btnG=Search"; string search = string.Format(raw,
HttpUtility.UrlEncode(searchTerm)); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(search); using (HttpWebResponse
response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader
reader = new StreamReader(response.GetResponseStream(),
Encoding.ASCII))
{
string html = reader.ReadToEnd();
//return FindPosition(html, url);
fillgoogle(html);
}
}
}
//New Fill Google
void fillgoogle(string html)
{
listBox1.Items.Clear();
// string pattern = #"h3 class=";
string pattern = "<h3 class=\"r\"><a href=";
/*for (int i = 0; i < 10; i++)
{
int start;
int end;
int pos;
pos = html.IndexOf(pattern);
start = html.IndexOf("href=", pos);
end = html.IndexOf("/", start + 15);
ListBox1.Items.Add(prepare(html.Substring(start + 6, end - start)));
html = html.Substring(end);
}*/
// int start;
int end;
int pos;
// string[] strUrl;
pos = html.IndexOf(pattern);
string[] Arr = Regex.Split(html, pattern);
for (int x = 1; x <= Arr.Length - 1; x++)
{
//string find = Arr[x].ToString();
//string RealData=find.Substring
// listBox1.Items.Add(Arr[x].ToString());
end = Arr[x].IndexOf("/", 38);
str1 = Arr[x].Substring(0, end);
// strUrl = Regex.Split(Arr[1], "&");
//string n = string.Join("/url?q=", Arr);
str1 = str1.Replace('"', ' ');
str1 = str1.Trim();
str1 = str1.Remove(0, 7).ToString();
listBox1.Items.Add(str1);
// ListBox1.Items.Add(Arr[x].Substring(0, end));
if (x == 10)
{
break;
}
}
}
void finalList()
{
listBox2.Items.Clear();
for (int i = 0; i < listBox1.Items.Count; i++)
{
string Link = listBox1.Items[i].ToString();
if (Link.IndexOf("&") != -1)
{
int end = Link.IndexOf("&");
string real = Link.Substring(0, end);
listBox2.Items.Add(real);
//MessageBox.Show(real);
}
}
}
string prepare(string url)
{
string temp;
int i;
i = url.IndexOf("//");
int j;
j = url.IndexOf("/", i + 3);
temp = url.Substring(0, j);
return (temp);
}
private static int FindPosition(
string html, Uri url)
{// h3 class=\"r\"><a href=\"http://www.godaddy.com/\
string lookup = "(<h3 class=r><a href=\")(\\*)";
MatchCollection matches = Regex.Matches(html, lookup);
for (int i = 0; i < matches.Count; i++)
{
string match = matches[i].Groups[2].Value;
if (match.Contains(url.Host))
return i + 1;
} return 0;
}
private void button1_Click(object sender, EventArgs e)
{
richTextBox1.Text = "";
Uri url = new Uri("http://www.godaddy.com");
GetPosition(url, textBox1.Text);
finalList();
webPage page = new webPage();
page.URL = listBox2.Items[0].ToString();
page.Load(); //Load the text from the specified URL
label3.Visible = true;
linkLabel1.Visible = true;
label3.Text = listBox2.Items[0].ToString();
//Display the page TITLE on the screen
//richTextBox1.Text = "Title: " + page.Title + Environment.NewLine + Environment.NewLine;
//Display a list of INTERNAL links on the screen (to include external links, see below)
//richTextBox1.Text += "LINKS" + Environment.NewLine + "=====" + Environment.NewLine;
//foreach (String link in page.LinksArray)
//{
// richTextBox1.Text += link + Environment.NewLine;
//}
//Display the BODY TEXT on the screen
richTextBox1.Text += Environment.NewLine + page.Body;
//richTextBox1.Text += Environment.NewLine + page.Paragraph;
}
public class webPage
{
public String URL;
private String sTitle;
private String sBody;
private String sParagraph;
private ArrayList aList;
public String Title
{
get
{
return sTitle;
}
}
public ArrayList LinksArray
{
get
{
return aList;
}
}
public String Body
{
get
{
return sBody;
}
}
public String Paragraph
{
get
{
return sParagraph;
}
}
public void Load()
{
try
{
WebRequest objRequest = WebRequest.Create(this.URL);
WebResponse objResponse = objRequest.GetResponse();
StreamReader oSR = new StreamReader(objResponse.GetResponseStream());
string strContent = oSR.ReadToEnd();
this.sTitle = getTitle(strContent);
this.aList = fetchLinks(strContent, URL);
this.sBody = fetchText(strContent);
this.sParagraph = GetFirstParagraph(strContent);
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
private String getTitle(String sHTMLContent)
{
//Retrieve the title from the HTML code
return Regex.Match(sHTMLContent, "<title>(?<title>[^<]+)</title>", RegexOptions.IgnoreCase).Groups["title"].ToString();
}
private ArrayList fetchLinks(String sHTMLContent, String sURL)
{
//Find all the links in the HTML code and put them
//into an array
Match mMatch;
ArrayList aMatch = new ArrayList();
mMatch = Regex.Match(sHTMLContent, "href\\s*=\\s*(?:\"(?<1>[^\"]*)\"|(?<1>\\S+))", RegexOptions.IgnoreCase);
while (mMatch.Success)
{
String sMatch = processURL(mMatch.Groups[1].ToString(), sURL);
//Currently, this code only lists INTERNAL URLs. If you would
//like to include EXTERNAL URLs as well, comment out the fol-
//lowing IF statement EXCEPT the "aMatch.Add(sMatch);" line
if (sMatch.IndexOf(sURL) >= 0 && checkFormat(sMatch))
{
aMatch.Add(sMatch);
}
mMatch = mMatch.NextMatch();
}
return aMatch;
}
static string GetFirstParagraph(string s)
{
Match m = Regex.Match(s, #"<p>\s*(.+?)\s*</p>");
if (m.Success)
{
return m.Groups[1].Value;
}
else
{
return "";
}
}
private String fetchText(String s)
{
//Filter out HTML and JavaScript from the page, leaving only body text
s = Convert.ToString(Regex.Match(s, #"<body.+?</body>", RegexOptions.Singleline | RegexOptions.IgnoreCase)); //strip everything but <BODY>
s = Regex.Replace(s, "<script[^>]*?>.*?</script>", "", RegexOptions.Singleline | RegexOptions.IgnoreCase); //strip JavaScript
s = Regex.Replace(s, "<[^>]*>", ""); //strip HTML tags
s = Regex.Replace(s, "&(copy|#169);|&(quot|#34);|&(amp|#38);|&(lt|#60);&(gt|#62);|&(nbsp|#160);|&(iexcl|#161);|&(cent|#162);|&(pound|#163);|ยท", " "); //strip symbols
s = s.Replace("\t", " "); //strip tabs
s = Regex.Replace(s, "([\r\n])+", " "); //strip carriage returns
s = Regex.Replace(s, "\\s\\s+", " "); //strip white space (must be last)
return s.Trim();
}
private String processURL(String sInput, String sURL)
{
sURL = "http://" + Convert.ToString(sURL.Split('/').GetValue(2));
if (sInput.IndexOf("http://") < 0)
{
if (!sInput.StartsWith("/") && !sURL.EndsWith("/"))
{
return sURL + "/" + sInput;
}
else
{
if (sInput.StartsWith("/") && sURL.EndsWith("/"))
{
return sURL.Substring(0, sURL.Length - 1) + sInput;
}
else
{
return sURL + sInput;
}
}
}
else
{
return sInput;
}
}
private bool checkFormat(String sURL)
{
//List only pages ending with valid extensions
String[] validExt = { ".html", ".php", ".asp", ".htm", ".jsp", ".shtml", ".php3", ".aspx", ".pl", ".cfm" };
sURL = Convert.ToString(sURL.Split('?').GetValue(0));
foreach (String ext in validExt)
{
if (sURL.Substring(sURL.Length - ext.Length, ext.Length).ToLower() == ext) { return true; }
}
return false;
}
}
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
System.Diagnostics.Process.Start(label3.Text);
}
}
}
I do not see any attempts to call Alchemy API in your example but here's what you need to know:
Alchemy API uses standard Web Service calls with XML responses as default. However you can specify the response you want (JSON / RDP).
Here's the start-up documentation, Text Extraction and Requirements and URLGetText Endpoint (but check on the documentation website for the endpoint you need).

StreamWriter crashes with large text files in C#

I am using StreamWriter to write to a file. When I use a text with 10-50 word text, it works properly. However when i call the function again (it exceeds the 50 words) it crashes. Why is this happening? Any suggestions?
Here is the codes:
StreamWriter file = new StreamWriter("text6.txt");
file.Close();
int count = 0;
string temp = "";
string temp2 = "";
for (Match m = Regex.Match(str, qmatch2); m.Success; m = m.NextMatch())
{
temp = m.Value;
temp2 = Regex.Replace(temp, qmatch2, " . ");
str = Regex.Replace(str, temp, temp2);
}
if (temp.Contains(".") == false)
{
file = File.AppendText("text6.txt");
file.WriteLine(" " + temp);
count++;
file.Close();
}
Try this instead. You only need to create your StreamWriter immediately before you use it, and wrapping it in a using block will ensure that the stream is disposed immediately after you're done using it.
int count = 0;
string temp = "";
string temp2 = "";
for (Match m = Regex.Match(str, qmatch2); m.Success; m = m.NextMatch())
{
temp = m.Value;
temp2 = Regex.Replace(temp, qmatch2, " . ");
str = Regex.Replace(str, temp, temp2);
}
if (temp.Contains(".") == false)
{
using (var file = new StreamWriter("text6.txt"))
{
file.Write("text6.txt");
file.WriteLine(" " + temp);
}
count++;
}
Try this:
StreamWriter file;
try
{
file = new StreamWriter("text6.txt");
file.Close();
}
catch(Exception)
{
throw;
}

Categories

Resources