繁体   English   中英

根据正则表达式匹配索引插入字符串

[英]Insert into string based on Regex Match Index

我正在尝试在每一个正则表达式匹配项之前插入新行。 目前,我正在收到ArgumentOutOfRangeException。 我意识到对于我要插入的所有新行字符,索引都需要偏移(总共4个字符)。

你们知道这件事吗?

谢谢!

string origFileContents = File.ReadAllText(path);

string cleanFileContents = origFileContents.Replace("\n", "").Replace("\r", "");

Regex regex = new Regex(@"([0-9]{4}-[0-9]{2}-[0-9]{2}_[0-9a-zA-Z]*--)", RegexOptions.Singleline);
MatchCollection matches = regex.Matches(cleanFileContents);

int counter = 0;

foreach (Match match in matches)
{
    cleanFileContents.Insert(match.Index + 4 * counter, Environment.NewLine);
    counter++;
}

为什么不只是

cleanFileContents = regex.Replace(
    cleanFileContents,
    Environment.NewLine + "$0");

也就是说,您的问题可能是Environment.NewLine.Length可能是2,而不是4。编辑:而且,正如Cyborg指出的那样,Insert不会修改字符串,而是返回一个新字符串。

顺便说一句,如果您要匹配文字括号,则需要将其转义。

我至少在这些代码中看到了这些可识别的问题。

  1. "\\r\\n"是两个字符,而不是4。您应该使用Environment.NewLine.Length * counter

  2. cleanFileContents.Insert(...)返回一个新字符串,它不会修改“ cleanFileContents”。 您需要像cleanFileContents = cleanFileContents.Insert(...)

建议的修改:

string origFileContents = File.ReadAllText(path);

// Changed cleanFileContents to a StringBuilder for performance reasons
var cleanFileContents = New StringBuilder( origFileContents.Replace("\n", "").Replace("\r", "") );

Regex regex = new Regex(@"([0-9]{4}-[0-9]{2}-[0-9]{2}_[0-9a-zA-Z]*--)", RegexOptions.Singleline);
MatchCollection matches = regex.Matches(cleanFileContents.ToString());

int counter = 0;

foreach (Match match in matches)
{
    cleanFileContents.Insert(match.Index + Environment.NewLine.Length * counter, Environment.NewLine);
    counter++;
}

var result = cleanFileContents.ToString()

我不遵循逻辑
match.Index + 4 *计数器
您知道*在+之前应用吗?

与Cyborgx37类似-开始时未发布
ReadAllLines拆分为换行可能更快

Regex regex = new Regex(@"([0-9]{4}-[0-9]{2}-[0-9]{2}_[0-9a-zA-Z]*--)", RegexOptions.Singleline);
StringBuilder sbAll = new StringBuilder();
StringBuilder sbLine = new StringBuilder();
foreach (string line in System.IO.File.ReadAllLines("path"))
{
    sbLine.Append(line);
    MatchCollection matches = regex.Matches(line);

    int counter = 0;

    foreach (Match match in matches)
    {
        sbLine.Insert(match.Index + Environment.NewLine.Length * counter, Environment.NewLine);
        counter++;
    }
    sbAll.Append(line);
    sbLine.Clear();
}

暂无
暂无

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

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