String Replace()/ regex replace - 替换字符串数组中的字符串?

时间:2012-04-13 16:17:35

标签: c# regex arrays string replace

我正在编写一个从csv文件读入的控制台应用程序,并将文件中的每个元素存储到一个字符串数组中。有一种方法我想迭代数组中的每个字符串并删除所有非字母字符和空格。我使用regex.replace()使用字符串成功完成此操作,但是一旦我尝试使用字符串数组,它就会改变。然后我继续尝试使用string.replace(),但无济于事。我认为正则表达式路径是更好的选择,但我还没有成功。如果有人能帮助我,我会非常感激。到目前为止,这是我的代码:

    public static string[] ChangeAddress(string[] address)
    {
        for (int i = 0; i < address.Length; i++)
        {
            Regex.Replace(i, @"(\s-|[^A-Za-z])", ""); 
            System.Console.WriteLine(address[i]);
        }
        return address;
    }

    static void Main(string[] args)
    {
        string[] address = null;
        //try...catch read file, throws error if unable to read
        //reads file and stores values in array
        try
        {
            StreamReader sr = new StreamReader("test.csv");
            string strLine = "";
            //while not at the end of the file, add to array
            while (!sr.EndOfStream)
            {
                strLine = sr.ReadLine();
                address = strLine.Split(',');
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("File could no be read:");
            Console.WriteLine(e.Message);
        }

        //calls ChangeAddress method
        ChangeAddress(address);
    }

csv文件包含以逗号分隔的不同地址。我的目标是删除号码,只留下街道名称。例如,原始字符串可能是123假的,目标是删除“123”,因此它将被替换为“假”。我想对数组中的每个元素执行此操作。

3 个答案:

答案 0 :(得分:2)

您需要在替换时对结果执行某些操作,类似下面的内容应该修复它。

public static string[] ChangeAddress(string[] address)
{
    for (int i = 0; i < address.Length; i++)
    {
        address[i] = Regex.Replace(address[i], @"(\s-|[^A-Za-z])", ""); 
        System.Console.WriteLine(address[i]);
    }
    return address;
}

这里的关键是你必须将值传递给RegEx.Replace并更新你的数组。

答案 1 :(得分:1)

除了Mitchel的回答,这是一个问题:

StreamReader sr = new StreamReader("test.csv");
string strLine = "";

//while not at the end of the file, add to array
while (!sr.EndOfStream)
{
   strLine = sr.ReadLine();
   address = strLine.Split(',');
}

...可以替换为File.ReadAllLines

addresses = File.ReadAllLines("test.csv");

您可以使用File.ReadLines并动态修复地址:

var addresses = new List<string>();
foreach(var address in File.Readlines("test.csv"))
{
    var corrected = Regex.Replace(address, @"(\s-|[^A-Za-z])", "");
    addresses.Add(corrected);
}

答案 2 :(得分:0)

为什么不在将strlin引入地址数组之前将其替换为strLine?您可以执行以下操作:

`Regex.Replace(strLine, @"(\s-|[^A-Za-z])", "");`
`address = strLine.Split(',');`

当然,你可能想要修改你的正则表达式而不是删除','。