我对c#相当新,我正在开展一个小项目,但却陷入了困境。我有一个包含一些汇编代码的文件。我希望我的程序在这个文件中搜索一个字符串,实际上是在我的字符串之后的值。我正在寻找的其中一个字符串是:
setproperty QName(PackageNamespace(""), "font")
getlocal 4
pushint
我的搜索代码是:
private void searchFile(String searchText)
{
System.IO.StreamReader reader = new System.IO.StreamReader(file);
String text = reader.ReadToEnd();
if (Regex.IsMatch(text, searchText))
{
MessageBox.Show(searchText + " was found in the given file", "Finally!!");
}
else
{
MessageBox.Show("Sorry, but " + searchText + " could not be found in the given file", "No Results");
}
}
//when i click a button//
searchFile(@"setproperty QName(PackageNamespace(""""), ""font"")
getlocal 4
pushint ");
我知道字符串在文件中但结果却找不到。我不知道引号或标签是否是引号或标签。
以下是文件的一部分:
getlocal 4
pushstring "Verdana"
setproperty QName(PackageNamespace(""), "font")
getlocal 4
pushint 16764170
setproperty QName(PackageNamespace(""), "color")
getlocal 4
pushbyte 12
setproperty QName(PackageNamespace(""), "size")
我的第二个问题是如何在搜索结果后得到第一个int的值?
提前致谢。
-Leen
答案 0 :(得分:2)
你应该改变你的方法:
private static string searchFile(String searchText)
{
System.IO.StreamReader reader = new System.IO.StreamReader("test.txt");
String text = reader.ReadToEnd();
int poz = text.IndexOf(searchText);
if (poz >= 0)
{
int start = poz + searchText.Length;
int end = text.IndexOf("\n", start);
Console.WriteLine(searchText + " was found in the given file", "Finally!!");
return text.Substring(start, end - start);
}
else
{
Console.WriteLine("Sorry, but " + searchText + " could not be found in the given file", "No Results");
return string.Empty;
}
}
电话:
string val = searchFile("setproperty QName(PackageNamespace(\"\"), \"font\")\r\n\r\n getlocal 4\r\n pushint ");
答案 1 :(得分:0)
所以我认为你可能会用到VB.net。基于C语言(如c#)使用反斜杠字符“\”作为转义字符。 因此,在搜索字符串中的双引号时,您需要使用\“。
来转义它我相信你所寻找的是:
searchFile(@"setproperty QName(PackageNamespace(\"\"), \"font\")
getlocal 4
pushint ");
但这并不是一个正则表达式,这正是Regex类的意思。所以我会(不是真的,我会清理一下,比如混合我的UI和bizlogic)这样做:
// Added String as the function type so you can return the matched "Integer" as a string, you could always do a Int32.TryParse(...)
private String searchFile(String file, String searchText)
{
System.IO.StreamReader reader = new System.IO.StreamReader(file);
String text = reader.ReadToEnd();
int32 index = text.IndexOf(searchText);
if (index >= 0) //We could find it at the very beginning
{
MessageBox.Show(searchText + " was found in the given file", "Finally!!");
int32 start = index + searchText.Length;
int32 end = Regex.Match(text, "[\n\r\t]", index).Index; // This will search for whitespace
String value = text.Substring(start, end - start);
// Now you can do something with your value, like...
return value;
}
else
{
MessageBox.Show("Sorry, but " + searchText + " could not be found in the given file", "No Results");
return "";
}
}