如何在C#中编写代码以读取文件中的某些单词 [英] How do I writte a code in C# for read some words from a file
问题描述
您好,
我必须在C#中写一个序列。 Dat必须从文件中读取(不管是什么类型的文件),只是一些...之间的单词。
EX:ID配置:1423AAA结束配置
ID配置:242gggg结束配置
---------
我必须从每一行得到dat1423AAA。
结果必须放在一个字符串中(我认为是一个loooong字符串)。
请帮帮我:(
Sry for my english。
我尝试过:
从StreamReader开始sr = new StreamReader(文件);
....
我无法找到条件:(
你应该能够在互联网上找到答案,例如:< br $> b $ b
c# - 阅读一个单词的文本文件 - Stack Overflow [ ^ ]
这实际上取决于数据是,如果它重复。
如果您的数据总是格式为
... ID Config:nnnnaaa end config。 ..然后我会使用正则表达式:
(?< = ID Config:\ s +)\ w +(? = \ s)会这样做:
私人 static 正则表达式findID = 新正则表达式(
(?< = ID Config:\\\\ +)\\\\ + +(?= \\止),
RegexOptions .Multiline
| RegexOptions.CultureInvariant
| RegexOptions.Compiled
);
...
MatchCollection ms = findID.Matches(InputText);
foreach (匹配m in ms)
{
Console。的WriteLine(m.Value);
}
如果您是初学者,并且只是使用像regex这样的工具而感到困惑,您可能需要考虑其他格式,如XML。在XmlSerializer或DataContractSerializer上搜索文章
- 如果你花时间评估选项,它在.Net中很容易读写Xml ...
Hello,
I have to writte a sequence in C#. Dat have to read from a file (does not matter what kind of file), just the words between some ... words.
EX: "ID Config: 1423AAA end config
ID Config: 242gggg end config"
---------
And i have to get just dat "1423AAA", from each line.
The results must be put in one string (I think a loooong string).
Please help me :(
Sry for my english.
What I have tried:
Start with StreamReader sr = new StreamReader(file);
....
and i can't find the condition :(
You should really be able to find the answer on the Internet, eg,:
c# - Reading a text file word by word - Stack Overflow[^]
It really depends on how consistent the data is, and if it's repeated.
If your data is always of the form
... ID Config: nnnnaaa end config ...Then I'd use a regex:
(?<=ID Config:\s+)\w+(?=\s)Would do it:
private static Regex findID= new Regex( "(?<=ID Config:\\s+)\\w+(?=\\s)", RegexOptions.Multiline | RegexOptions.CultureInvariant | RegexOptions.Compiled ); ... MatchCollection ms = findID.Matches(InputText); foreach (Match m in ms) { Console.WriteLine(m.Value); }
If you are a beginner and you are already confused just by using a tool like regex you might want to consider alternative formats like XML. Search for articles on XmlSerializer or DataContractSerializer
- its really easy to read and write Xml in .Net if you take the time to evaluate the option ...
这篇关于如何在C#中编写代码以读取文件中的某些单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!