我正在编写一个控制台应用程序,它从csv文件读入并将文件中的每个元素存储到一个字符串数组中。有一种方法需要遍历数组中的每个字符串,并删除所有非alpha字符和空格。我使用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”,因此它将被替换为“假”。我想对数组中的每个元素执行此操作。
您是否阅读过[Regex.Replace]的MSDN页面(http://msdn.microsoft.com/zh-cn/library/h0y2x3xs.aspx)? (A)它_returns_一个字符串和(B)不接受一个整数作为第一个参数,所以这将不会按原样编译。 – 2012-04-13 16:26:44
除非您的实际代码与本示例有所不同,否则您只会从地址阵列中的文件中获取最后一个地址。您在while循环的每次迭代中覆盖它。 – pstrjds 2012-04-13 16:31:39