使用带条件的正则表达式在每个 n 个字符后拆分字符串,C#

Split string after each n chars using Regex with condition, C#

如果字符串的长度超过 'n' 个字符,我需要用新行拆分字符串。在每个 'n' 个字符之后应该有一个新行。

我编写了适用于这种情况的代码:

string text = "11+222+333+44444+555555+6666666";
var regex = new Regex(@".{"+n+"}");
text = regex.Replace(text, "$&" + "\r\n"); //result

但是还有一个要求。假设字符串始终具有类似 digitplus 的格式(在开头和结尾没有“+”),字符串仍应在 'n' 字符后用新行拆分,但它不能分割数字。 IE。输出不能是这样的 (n=15):

11+222+333+444
4+555555+66666
6

相反,它应该拆分,以便数字保持完整且行长度不超过 n:

11+222+333
4444+555555
+666666

此外,如果该行被分割,它不应该在开头和结尾包含 '+' neigher。最终输出:

11+222+333
4444+555555
666666

谢谢!

string text = "11+222+333+44444+555555+6666666";
var regex = new Regex(@"(.{1," + n + @"})(\+|$)");
text = regex.Replace(text, "" + "\r\n"); //result

您尝试匹配 1...n 个字符 (,{1,n})。你把它放在第一个捕获组中。然后你有另一个捕获组,它可以是 + 或字符串的结尾 ($)。替换时,保留第一个捕获组(带数字的那个)的文本 (</code>) 但删除第二个捕获组(注意不能真正删除字符串的末尾)</p> <p>请注意,有一个有趣的副作用,那就是好的。如果你有(例如)n = 3,你会得到</p> <pre><code>11+222 333 44444 555555 6666666

没关系...最好将数字保持在一起。发生的事情是正则表达式不是 "anchored" 左边的任何东西,所以当它最后看到 4444+555555 时它匹配 4444+,并替换只有那部分。

Regex 听起来有点矫枉过正,非专业的 Regex 用户很难维护。我会推荐一些类似下面的代码(这是空气代码;换句话说,我只是在这里输入它):

// container of final strings
List<string> strings = new List<string>();
// original string
string original = "11+222+333+44444+555555+6666666";
// max length of new string
int n = 12;
// split to number parts
string[] numbers = original.Split("+");
// current output string
string current = ""
foreach (string number in numbers)
{
    if ((number.Length + current.Length) >= n)
    {
        // can't add this one to current so store current and start new one
        strings.Add(current);
        current = number;
    }
    else
    {
        if (!string.IsNullOrEmpty(current)
        {
            current = current + "+" + number;
        }
        else
        {
            current = number;
        }
    }
}
// at end, add the final current if not empty
if (!string.IsNullOrEmpty(current))
{
    strings.Add(current);
}