I am trying to make my program display the text above the input text which matches a pattern I set.
For example, if user input 'FastModeIdleImmediateCount"=dword:00000000', I should get the closest HKEY above, which is [HKEY_CURRENT_CONFIG\System\CurrentControlSet\Enum\SCSI\Disk&Ven_ATA&Prod_TOSHIBA_MQ01ABD0\4&6a0976b&0&000000] for this case.
[HKEY_CURRENT_CONFIG\System\CurrentControlSet\Enum\SCSI\Disk&Ven_ATA&Prod_TOSHIBA_MQ01ABD0\4&6a0976b&0&000000]
"StandardModeIdleImmediateCount"=dword:00000000
"FastModeIdleImmediateCount"=dword:00000000
[HKEY_CURRENT_CONFIG\System\CurrentControlSet\SERVICES]
[HKEY_CURRENT_CONFIG\System\CurrentControlSet\SERVICES\TSDDD]
[HKEY_CURRENT_CONFIG\System\CurrentControlSet\SERVICES\TSDDD\DEVICE0]
"Attach.ToDesktop"=dword:00000001
Could anyone please show me how I can code something like that? I tried playing around with regular expressions to match text with bracket, but I am not sure how to make it to only search for the text above my input.
I'm assuming your file is a .txt file, although it's most probably not. But the logic is the same.
It is not hard at all, a simple for() loop would do the trick.
Code with the needed description:
string[] lines = File.ReadAllLines(#"d:\test.txt");//replace your directory. We're getting all lines from a text file.
string inputToSearchFor = "\"FastModeIdleImmediateCount\"=dword:00000000"; //that's the string to search for
int indexOfMatchingLine = Array.FindIndex(lines, line => line == inputToSearchFor); //getting the index of the line, which equals the matchcode
string nearestHotKey = String.Empty;
for(int i = indexOfMatchingLine; i >=0; i--) //looping for lines above the matched one to find the hotkey
{
if(lines[i].IndexOf("[HKEY_") == 0) //if we find a line which begins with "[HKEY_" (that means it's a hotkey, right?)
{
nearestHotKey = lines[i]; //we get the line into our hotkey string
break; //breaking the loop
}
}
if(nearestHotKey != String.Empty) //we have actually found a hotkey, so our string is not empty
{
//add code...
}
You could try to split the text into lines, find the index of the line that contains your text (whether exact match or regex is used doesn't matter) and then backsearch for the first key. Reverse sorting the lines first might help.
Related
I've a list of paragraphs. Each paragagraph can contain Text. I'm trying to search for a string that may be as whole within a single paragraph, or spread across multiple paragraphs with as bad case where each letter is different paragraph.
public List<WordParagraph> FindText(string text) {
List<WordParagraph> list = new List<WordParagraph>();
var found = false;
Paragraph currentParagraph = null;
foreach (var paragraph in this.Paragraphs) {
//if (currentParagraph == null) {
// currentParagraph = paragraph._paragraph;
//} else {
// if (currentParagraph != paragraph._paragraph) {
// found = false;
// }
//}
// paragraph.Text
// logic missing to find text that can start within some paragraph.Text, but
// can span across multiple paragraphs
// for example searching for text "This Is MyTest" within 4 paragraphs that
// may be written like
// paragraph.Text = "Thi"
// paragraph.Text = "s Is"
// paragraph.Text = " MyTes"
// paragraph.Text = "t"
}
return list;
}
I've tried some logic around foreach char in text, and nested loop over text from the paragraph.text but the logic was failing me.
To give you a bit of background. Consider a Word Document that has a single sentence - one long sentence but each word, or even letter is formatted differently - different font size, bold, underline or whatever. It looks like this:
Now what Word actually saved in the file is a single paragraph, but each paragraph has multiple "runs". The run contains a Text element. Each text element contains the text that you see in Word, but due to formatting of possibly even each word it can be split into many many small Text properties.
Now in my example, I've simplified the logic and for me, each "run" is a paragraph with a text. So List of WordParagraphs is a list of runs within Screenshot you see.
Now I need to find a string "I have that" from the whole sentence you see in word. That means I need to go thru all paragraphs, find the first letter that matches and then check if next letter matches as well, if not I need to start again.
My brain is having hard time to grasp this logic in code.
I have a text file with over 12,000 lines. In that file I need to replace certain lines.
Some lines begin with a ;, some have random words, some start with space. However, I am only concerned with the two types of lines I describe below.
I have a line like
SET avariable:0 ;Comments
and I need to replace it to look like
set aDIFFvariable:0 :Integer // comments
The only CASE that is necessary is in the word Integer I needs to be capitalized.
I also have
String aSTRING(7) ;Comment
that needs to look like
STRING aSTRING(7) :array [0..7] of AnsiChar; // Comments
I need to keep all the spacing the same.
Here is what I have so far
static void Main(string[] args)
{
string text = File.ReadAllText("C:\\old.txt");
text = text.Replace("old text", "new text");
File.WriteAllText("C:\\new.txt", text);
}
I think I need to use REGEX, which I have tried to make for my first example:
\s\s[set]\s*{4}.*[:0]\s*[;].* <-- I now know this is invalid - please advise
I need help with properly setting up my program to find and replace those lines. Should I read one line at a time and if it matches then do something? I am confused really as to where to start.
BRIEF pseudo code of what I want to do
//open file
//step through file
//if line == [regex] then add/replace as needed
//else, go to next line
//if EOF, close file
Taking a stab at this separately because each line is so radically different that capturing both in the same expression will be a nightmare.
To match your first example and replace it:
String input = "SET avariable:0 ;Comments";
if (Regex.IsMatch(input, #"\s?(set)\s*(\w+):?(\d)\s+;?(.*)?"))
{
input = Regex.Replace(input, #"\s?(set)\s*(\w+):?(\d)\s+;?(.*)?", "$1 $2:$3 :Integer // $4";
}
Give that a shot (Play with it here: http://regex101.com/r/zY7hV2)
To match your second example and replace it:
String input = "String aSTRING(7) ;Comments";
if (Regex.IsMatch(input, #"\s?(string)\s*(\w+)\((\d)\)\s*;(.*)"))
{
input = Regex.Replace(input, #"\s?(string)\s*(\w+)\((\d)\)\s*;(.*)", "$1 $2($3) :array [0..$3] of AnsiChar; // $4";
}
And play around with this one here: http://regex101.com/r/jO5wP5
im trying to make a code that searches through a textfile for a certain phrase and then populates a textbox with the line if a phrase occurs in that. There are no errors with this code, but it doesn't work at all. Anyone know what is wrong? I'm not too sure if what i'm doing is remotely correct.
{
tuitDisplayTextBox.Text = "";
string[] tuitFilePath = File.ReadAllLines(Server.MapPath("~") +"/App_Data/tuitterMessages.txt");
for (int i = 0; i < tuitFilePath.Length; i++)
{
if (tuitFilePath[i].Contains(searchTextBox.Text))
{
tuitDisplayTextBox.Text += tuitFilePath[i];
}
}
Your solution should work... for the last line that matches, and only that one.
LINQ can help you here, though. Here's a solution that should work.
tuitDisplayTextBox.Text =
File.ReadLines(Server.MapPath("~") +"/App_Data/tuitterMessages.txt")
.Where(n => n.Contains(searchTextBox.Text)).Aggregate((a, b) =>
a + Enviroment.NewLine + b);
Here, what it does is it reads the lines of the file into an IEnumerable<string>, and then I filter that with the Where method, which basically means "if the condition is true for this element, add this element to the list of things to return, else don't add it". And then Aggregate is a bit more complicated. Basically what it does is it takes the first two items from the collection, and then pass a lambda through them that returns a value. Then call the lambda again with that result and the third element. And then it takes that result and calls it with the fourth element. And so on.
Here's some code more similar to yours that will also work:
tuitDisplayTextBox.Text = "";
IEnumerable<string> lines =
File.ReadAllLines(Server.MapPath("~") +"/App_Data/tuitterMessages.txt");
StringBuilder sb = new StringBuilder
foreach (string line in lines)
{
if (line.Contains(searchTextBox.Text))
{
sb.AppendLine(line);
}
}
tuitDisplayTextBox.Text = sb.ToString();
Here it's a bit different. First it reads all the lines into an IEnumerable<string> called lines. Then it makes a StringBuilder object (basically a mutable string). After that, it foreaches the lines in the IEnumerable<string> (I thought it was more appropriate here) and then if the line contains the text you want, it adds that line and a newline to the StringBuilder object. After that, it sets your textbox's text to the result of all of that, by getting the string representation of the StringBuilder instance.
And if you really want a for loop, here's the code modified to use a for loop:
tuitDisplayTextBox.Text = "";
string[] lines =
File.ReadAllLines(Server.MapPath("~") +"/App_Data/tuitterMessages.txt");
StringBuilder sb = new StringBuilder
for (int i = 0; i < lines.Length; i++)
{
if (lines[i].Contains(searchTextBox.Text))
{
sb.AppendLine(lines[i]);
}
}
tuitDisplayTextBox.Text = sb.ToString();
Please note that File.ReadAllLines break sentences at '\r' or '\n'.
So, if you search for "hello world" and this text is break in the file into 2 lines (e.g. "... hello /n world" your code will failed...
So, use the ReadAllText() instead, return one string contains all file's text.
Still, you might face sometimes problems with file encoding, but this is another issue.
After, and if, you find the text you are searching for you can use the ReadAllLines to decide about the location of the text.
I have converted an asp.net c# project to framework 3.5 using VS 2008. Purpose of app is to parse a text file containing many rows of like information then inserting the data into a database.
I didn't write original app but developer used substring() to fetch individual fields because they always begin at the same position.
My question is:
What is best way to find the index of substring in text file without having to manually count the position? Does someone have preferred method they use to find position of characters in a text file?
I would say IndexOf() / IndexOfAny() together with Substring(). Alternatively, regular expressions. It the file has an XML-like structure, this.
If the files are delimited eg with commas you can use string.Split
If data is: string[] text = { "1, apple", "2, orange", "3, lemon" };
private void button1_Click(object sender, EventArgs e)
{
string[] lines = this.textBoxIn.Lines;
List<Fruit> fields = new List<Fruit>();
foreach(string s in lines)
{
char[] delim = {','};
string[] fruitData = s.Split(delim);
Fruit f = new Fruit();
int tmpid = 0;
Int32.TryParse(fruitData[0], out tmpid);
f.id = tmpid;
f.name = fruitData[1];
fields.Add(f);
}
this.textBoxOut.Clear();
string text=string.Empty;
foreach(Fruit item in fields)
{
text += item.ToString() + " \n";
}
this.textBoxOut.Text = text;
}
}
The text file I'm reading does not contain delimiters - sometimes there spaces between fields and sometimes they run together. In either case, every line is formatted the same. When I asked the question I was looking at the file in notepad.
Question was: how do you find the position in a file so that position (a number) could be specified as the startIndex of my substring function?
Answer: I've found that opening the text file in notepad++ will display the column # and line count of any position where the curser is in the file and makes this job easier.
You can use indexOf() and then use Length() as the second substring parameter
substr = str.substring(str.IndexOf("."), str.Length - str.IndexOf("."));
Ok I have an autocomplete/string matching problem to solve. I have an expression string typed in by a user into a text box, e.g.
More detail:
Expression textbox has string
"Buy some Al"
and client has a list of suggestions given by a server after a fuzzy match which populate a listbox
All Bran, Almonds, Alphabetti Spaghetti
now on the GUI I have a nice intellisense style autocomplete, but I need to wire up the "TAB" action to perform the complete. So if the user presses TAB and "All Bran" was the top suggestion, the string becomes
"Buy some All Bran"
e.g. the string "Al" was substituted for the top match "All Bran"
It's more than a simple string split on the expression to match the suggestions, as the expression text could be this
"Buy some All Bran and Al"
with suggestions
Alphabetti Spaghetti
In which case I'd expect the final Al to be substituted with the top match so the result becomes
"Buy some All Bran and Alphabetti Spaghetti"
I'm wondering how to do this simply in C# (Just the C# string manipulation, not GUI code) without going back to the server and asking for a substitution to be made.
You could do this with regex, but it doesn't seem necessary. The following solution assumes that the suggestion will always be preceded by a space (or start at the beginning of the sentence). If that's not the case then you'll need to share more examples to get the rules down.
string sentence = "Buy some Al";
string selection = "All Bran";
Console.WriteLine(AutoComplete(sentence, selection));
sentence = "Al";
Console.WriteLine(AutoComplete(sentence, selection));
sentence = "Buy some All Bran and Al";
selection = "Alphabetti Spaghetti";
Console.WriteLine(AutoComplete(sentence, selection));
Here is the AutoComplete method:
public string AutoComplete(string sentence, string selection)
{
if (String.IsNullOrWhiteSpace(sentence))
{
throw new ArgumentException("sentence");
}
if (String.IsNullOrWhiteSpace(selection))
{
// alternately, we could return the original sentence
throw new ArgumentException("selection");
}
// TrimEnd might not be needed depending on how your UI / suggestion works
// but in case the user can add a space at the end, and still have suggestions listed
// you would want to get the last index of a space prior to any trailing spaces
int index = sentence.TrimEnd().LastIndexOf(' ');
if (index == -1)
{
return selection;
}
return sentence.Substring(0, index + 1) + selection;
}
Use string.Join(" and ", suggestions) to create your replacement string and then string.Replace() to do substitution.
You can add the listbox items in the array and while traversing through array, once a match is found, break the loop and get out of it and display the output.