如果字符串包含特殊字符,StreamReader将空行存储在列表中

本文关键字:存储 列表 包含 字符串 特殊字符 StreamReader 如果 | 更新日期: 2023-09-27 18:04:26

文本文件包含数百行这样的代码,几乎所有这些代码都存储在列表中。但是包含'-','&'或点('.')等字符的行将作为空行添加到列表中。从下面的行中:1,2,7,8,10 &第11行将被正确存储,其余的将被空白存储。之后,当我尝试将列表加载到下拉列表中时,下拉列表中也有空白值。

代码:

string singleLineSchedule;
List<string> courses = new List<string>();
public List<string> LoadStudentCourses()
{
try
{
    fileLoader = new StreamReader(@"C:'TestSchedule.txt", Encoding.Default, true);
    //Read one line at a time
    while ((singleLineSchedule = fileLoader.ReadLine()) != null)
    {
        //Will store any text from each line that is in between '> & </option>, for example: '>Course1</option>
        courses.Add(GetTextBetween(singleLineSchedule, "'>", "</option>"));
    }
}
catch
{
    courses.Add("Error loading schedule file");
}
fileLoader.Dispose();
return courses;
}
public static String GetTextBetween(String source, String leftWord, String rightWord)
{
return Regex.Match(source, String.Format(@"{0}(?<words>['w's]+){1}", leftWord, rightWord), RegexOptions.IgnoreCase).Groups["words"].Value;
}

文本文件中获取信息的部分(它们都是选项类型):

 <option>year 1</option>
 <option>second year</option>
 <option>class 1 containing a special-character</option>
 <option>class 2 containing special-characters & such</option>
 <option>class 3 containing a special-character</option>
 <option>class 4 containing a special-character</option>
 <option>third year</option>
 <option>fourth year</option>
 <option>fifth year with a dot.</option>
 <option>value 4</option>
 Biology</option>

如果字符串包含特殊字符,StreamReader将空行存储在列表中

'w's在regex中不允许其他字符,但a-z, a-z, 0-9,空白,所以如果字符串中有其他内容,GetTextBetween的返回值为空。