C# - 从文件中搜索和替换字符串的有效方法

时间:2015-02-18 03:28:52

标签: c# regex string

我有一个文本文件,我希望搜索是否存在一组行并更新/覆盖它们,或者如果这些行不存在,请添加它们。

这是文本文件。

#
# Virtual Hosts
#
# If you want to maintain multiple domains/hostnames on your
# machine you can setup VirtualHost containers for them. Most configurations
# use only name-based virtual hosts so the server doesn't need to worry about
# IP addresses. This is indicated by the asterisks in the directives below.
#
# Please see the documentation at 
# <URL:http://httpd.apache.org/docs/2.2/vhosts/>
# for further details before you try to setup virtual hosts.
#
# You may use the command line option '-S' to verify your virtual host
# configuration.

#
# Use name-based virtual hosting.
#
##NameVirtualHost *:80

#
# VirtualHost example:
# Almost any Apache directive may go into a VirtualHost container.
# The first VirtualHost section is used for all requests that do not
# match a ServerName or ServerAlias in any <VirtualHost> block.
#
##<VirtualHost *:80>
    ##ServerAdmin postmaster@dummy-host.localhost
    ##DocumentRoot "C:/xampp/htdocs/dummy-host.localhost"
    ##ServerName dummy-host.localhost
    ##ServerAlias www.dummy-host.localhost
    ##ErrorLog "logs/dummy-host.localhost-error.log"
    ##CustomLog "logs/dummy-host.localhost-access.log" combined
##</VirtualHost>

##<VirtualHost *:80>
    ##ServerAdmin postmaster@dummy-host2.localhost
    ##DocumentRoot "C:/xampp/htdocs/dummy-host2.localhost"
    ##ServerName dummy-host2.localhost
    ##ServerAlias www.dummy-host2.localhost
    ##ErrorLog "logs/dummy-host2.localhost-error.log"
    ##CustomLog "logs/dummy-host2.localhost-access.log" combined
##</VirtualHost>

<VirtualHost *:80>
    ServerAdmin postmaster@dummy-host2.localhost
    DocumentRoot "C:/xampp/htdocs/dummy-host2.localhost"
    ServerName dummy-host2.localhost
    ServerAlias www.dummy-host2.localhost
    #ErrorLog "logs/dummy-host2.localhost-error.log"
    CustomLog "logs/dummy-host2.localhost-access.log" combined
</VirtualHost>

这是骨架代码。我首先打开文本文件,然后将其读到最后,以便我可以使用Regex类。 (我选择了这个,因为代码看起来更干净简洁,而不是以C方式进行循环)。但事情并非如此简单,因为我需要首先检查一组线。

    StreamReader reader = new StreamReader(path);
    string content = reader.ReadToEnd();
    reader.Close();

    // Replace the strings using Regex replace method
    StreamWriter writer = new StreamWriter(path);
    writer.Write(content);
    writer.Close();

给定端口号,我将其附加到此模式

string virtualHost = "<VirtualHost *:" + cls_globalvariables.portNumber + ">";

我用过

Match match = Regex.Match(content, virtualHost);

找到搜索模式的索引。我还必须找到其结束标记的索引,并用这些行的更新版本替换它们。我没有搜索结束行的问题,但我确实有区分注释和未注释行的问题。

Regex.Match返回搜索模式的第一个匹配项,即搜索模式。我想做的是搜索没有评论的模式,但我该怎么做?我开始考虑使用C方案,例如从match.Index开始逐个字符地逐个循环,直到我检测到“\ r \ n”的分隔符。有没有一种有效的C#方法来解决这个问题?

1 个答案:

答案 0 :(得分:0)

您可以按照Jesse建议的方式进行操作,或者如果您想坚持使用正则表达式,只需将^放在正则表达式的开头并设置RegexOptions.Multiline

  

多线模式。更改^和$的含义,使它们分别在任何行的开头和结尾匹配,而不仅仅是整个字符串的开头和结尾。有关详细信息,请参阅正则表达式选项主题中的“多行模式”部分。