首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如果字符串包含特殊字符,则StreamReader在列表中存储空行

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

Stack Overflow用户
提问于 2014-05-21 07:48:16
回答 1查看 97关注 0票数 0

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

代码:

代码语言:javascript
复制
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;
}

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

代码语言:javascript
复制
 <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>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-05-21 09:38:08

\ regex中的W\s不允许其他字符,而只允许A、A、0-9和空格,因此如果字符串中有其他内容,则GetTextBetween的返回值为空。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23777130

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档