更改字符串的特定部分

时间:2014-03-23 09:47:02

标签: c# regex string split

在C#中,我得到了一个字符串,其格式如下:

a number|a number|a number,a number

例如:1 | 2 | 3,4

我认为每个数字都是字符串的不同部分。在前面的例子中,1是第一部分,2是第二部分,依此类推。

我希望能够在给定要更改的部分的索引的情况下替换字符串的特定部分。

String.Split做这件事并不难,但是那部分用逗号会让它变得单调乏味,因为那时我需要检查索引是3还是4,然后再用逗号分隔。 是否有一种更优雅的方式来切换字符串中的特定部分?也许以某种方式使用正则表达式?

编辑:我将添加一些我以前没写过的要求:

如果我想要例如取字符串的第3部分并将其替换为那里的数字并添加它2.例如1 | 2 | 3,4到1 | 2 | 5,4其中5是不是常数,而是取决于给定的输入字符串。

4 个答案:

答案 0 :(得分:1)

您可以创建以下方法

static string Replace(string input, int index, string replacement)
{
    int matchIndex = 0;
    return Regex.Replace(input, @"\d+", m => matchIndex++ == index ? replacement : m.Value);
}

用法:

string input = "1|2|3,4";
string output = Replace(input, 1, "hello"); // "1|hello|3,4

正如Eric Herlitz建议的那样,您可以使用其他正则表达式,即分隔符的否定。例如,如果您希望,|分隔符,则可以将\d+替换为[^,|]+正则表达式。如果您希望,|#分隔符,则可以使用[^,|#]正则表达式。

如果你需要做一些数学运算,你可以自由地这样做:

static string Replace(string input, int index, int add)
{
    int matchIndex = 0;
    return Regex.Replace(input, @"\d+", m => matchIndex++ == index ? (int.Parse(m.Value) + add).ToString() : m.Value );
}

示例:

string input = "1|2|3,4";
string output = Replace(input, 2, 2); // 1|2|5,4

你甚至可以使它成为通用的:

static string Replace(string input, int index, Func<string,string> operation)
{
    int matchIndex = 0;
    return Regex.Replace(input, @"\d+", m => matchIndex++ == index ? operation(m.Value) : m.Value);
}

示例:

string input = "1|2|3,4";
string output = Replace(input, 2, value => (int.Parse(value) + 2).ToString()); // 1|2|5,4

答案 1 :(得分:0)

使用Regex.Split作为输入,使用Regex.Match收集分隔符

string input = "1|2|3,4,5,6|7,8|9";
string pattern = @"[,|]+";

// Collect the values
string[] substrings = Regex.Split(input, pattern);

// Collect the delimiters
MatchCollection matches = Regex.Matches(input, pattern);

// Replace anything you like, i.e.
substrings[3] = "222";

// Rebuild the string
int i = 0;
string newString = string.Empty;
foreach (string substring in substrings)
{
    newString += string.Concat(substring, matches.Count >= i + 1 ? matches[i++].Value : string.Empty);
}

这将输出"1|2|3,222,5,6|7,8|9"

答案 2 :(得分:0)

试试这个(测试过):

public static string Replace(string input, int value, int index)
{
       string pattern = @"(\d+)|(\d+)|(\d+),(\d+)";

       return Regex.Replace(input, pattern, match =>
       {
            if (match.Index == index * 2) //multiply by 2 for | and , character.
            {
                return value.ToString();
            }

            return match.Value;
      });
 }

用法示例:

string input = "1|2|3,4";
string output = Replace(input, 9, 1);

更新了新要求:

public static string ReplaceIncrement(string input, int incrementValue, int index)
{
            string pattern = @"(\d+)|(\d+)|(\d+),(\d+)";

            return Regex.Replace(input, pattern, match =>
            {
                if (match.Index == index * 2)
                {
                    return (int.Parse(match.Value) + incrementValue).ToString();
                }

                return match.Value;
            });
 }

答案 3 :(得分:0)

试试这个:

    static void Main()
    {
        string input = "1|2|3|4,5,6|7,8|9|23|29,33";

        Console.WriteLine(ReplaceByIndex(input, "hello", 23));
        Console.ReadLine();
    }

    static string ReplaceByIndex(string input, string replaceWith, int index)
    {
        int indexStart = input.IndexOf(index.ToString());

        int indexEnd = input.IndexOf(",", indexStart);
        if (input.IndexOf("|", indexStart) < indexEnd)
            indexEnd = input.IndexOf("|", indexStart);

        string part1 = input.Substring(0, indexStart);
        string part2 = "";
        if (indexEnd > 0)
        {
            part2 = input.Substring(indexEnd, input.Length - indexEnd);
        }

        return part1 + replaceWith + part2;
    }

这是假设数字按升序排列。

相关问题