繁体   English   中英

如何避免使用多个regex.replace

[英]How to avoid using multiple regex.replace

目标是获取一个文本文件,将其规范化为仅包含所有大写字母,删除所有特殊字符,然后将任何新行转换为一个空格。

就我所知,这是我目前执行的混乱代码。

public string readTextFile(string fileName)
{
    Regex rgx = new Regex("[^A-Z ]");
    string txtFile = File.ReadAllText(fileName).ToUpper();

    txtFile = Regex.Replace(txtFile, @"\s+", " ", RegexOptions.Multiline);
    return rgx.Replace(txtFile, "");
}

寻找任何人来帮助清理此代码,提高效率,并可能将我的regex语句合并为一个。

您可以合并您的正则表达式,并像这样将Match方法与MatchEvaluator一起使用

public string readTextFile(string fileName)
{
    Regex rgx = new Regex("");
    string txtFile = File.ReadAllText(fileName).ToUpper();

    txtFile = Regex.Replace(txtFile, @"(\s+)|([^A-Z ])", 
                m=> m.Groups[2].Success ? string.Empty : " ",
                RegexOptions.Multiline);
    return txtFile;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM