仅使用Regex替换某些组

时间:2011-05-15 00:07:09

标签: c# regex replace

假设我有以下正则表达式:

-(\d+)-

我希望使用C#替换第1组(\d+)AA,以获取:

-AA-

现在我用以下方法替换它:

var text = "example-123-example";
var pattern = @"-(\d+)-";
var replaced = Regex.Replace(text, pattern, "-AA-"); 

但我真的不喜欢这个,因为如果我改变模式以匹配_(\d+)_,我将不得不用_AA_更改替换字符串,这违反DRY原则

我正在寻找类似的内容:

保持匹配的文字的确切位置,但是按this text更改第1组,将第2组更改为another text ...

修改
那只是一个例子。我只是在寻找一种做我上面所说的通用方式。

它适用于:

anything(\d+)more_text以及您可以想象的任何模式。

我想要做的只是替换群组,并保持其余的匹配。

8 个答案:

答案 0 :(得分:257)

一个好主意可能是将所有内容封装在组内,无论是否需要识别它们。这样你就可以在替换字符串中使用它们。例如:

var pattern = @"(-)(\d+)(-)";
var replaced = Regex.Replace(text, pattern, "$1AA$3"); 

或使用MatchEvaluator:

var replaced = Regex.Replace(text, pattern, m => m.Groups[1].Value + "AA" + m.Groups[3].Value);

另一种方式,略显凌乱,可能是使用lookbehind / lookahead:

(?<=-)(\d+)(?=-)

答案 1 :(得分:30)

您可以使用lookahead and lookbehind执行此操作:

var pattern = @"(?<=-)\d+(?=-)";
var replaced = Regex.Replace(text, pattern, "AA"); 

答案 2 :(得分:14)

我也需要这个,我为它创建了以下扩展方法:

public static class RegexExtensions
{
    public static string ReplaceGroup(
        this Regex regex, string input, string groupName, string replacement)
    {
        return regex.Replace(
            input,
            m =>
            {
                var group = m.Groups[groupName];
                var sb = new StringBuilder();
                var previousCaptureEnd = 0;
                foreach (var capture in group.Captures.Cast<Capture>())
                {
                    var currentCaptureEnd =
                        capture.Index + capture.Length - m.Index;
                    var currentCaptureLength =
                        capture.Index - m.Index - previousCaptureEnd;
                    sb.Append(
                        m.Value.Substring(
                            previousCaptureEnd, currentCaptureLength));
                    sb.Append(replacement);
                    previousCaptureEnd = currentCaptureEnd;
                }
                sb.Append(m.Value.Substring(previousCaptureEnd));

                return sb.ToString();
            });
    }
}

用法:

var input = @"[assembly: AssemblyFileVersion(""2.0.3.0"")][assembly: AssemblyFileVersion(""2.0.3.0"")]";
var regex = new Regex(@"AssemblyFileVersion\(""(?<version>(\d+\.?){4})""\)");


var result = regex.ReplaceGroup(input , "version", "1.2.3");

结果:

[assembly: AssemblyFileVersion("1.2.3")][assembly: AssemblyFileVersion("1.2.3")]

答案 3 :(得分:13)

如果您不想更改模式,可以使用匹配组的“组索引”和“长度”属性。

var text = "example-123-example";
var pattern = @"-(\d+)-";
var regex = new RegEx(pattern);
var match = regex.Match(text);

var firstPart = text.Substring(0,match.Groups[1].Index);    
var secondPart = text.Substring(match.Groups[1].Index + match.Groups[1].Length);
var fullReplace = firstPart + "AA" + secondPart;

答案 4 :(得分:3)

这是另一个不错的干净选项,不需要改变你的模式。

        var text = "example-123-example";
        var pattern = @"-(\d+)-";

        var replaced = Regex.Replace(text, pattern, (_match) =>
        {
            Group group = _match.Groups[1];
            string replace = "AA";
            return String.Format("{0}{1}{2}", _match.Value.Substring(0, group.Index - _match.Index), replace, _match.Value.Substring(group.Index - _match.Index + group.Length));
        });

答案 5 :(得分:0)

通过以下编码获得单独的小组替换。

.name::after {
  content: '.';
}
.name.rtl::before {
  content: '.';
}
.name.rtl::after {
  content: '';
}

答案 6 :(得分:0)

这是与Daniel相似的版本,但替换了多个匹配项:

public static string ReplaceGroup(string input, string pattern, RegexOptions options, string groupName, string replacement)
{
    Match match;
    while ((match = Regex.Match(input, pattern, options)).Success)
    {
        var group = match.Groups[groupName];

        var sb = new StringBuilder();

        // Anything before the match
        if (match.Index > 0)
            sb.Append(input.Substring(0, match.Index));

        // The match itself
        var startIndex = group.Index - match.Index;
        var length = group.Length;
        var original = match.Value;
        var prior = original.Substring(0, startIndex);
        var trailing = original.Substring(startIndex + length);
        sb.Append(prior);
        sb.Append(replacement);
        sb.Append(trailing);

        // Anything after the match
        if (match.Index + match.Length < input.Length)
            sb.Append(input.Substring(match.Index + match.Length));

        input = sb.ToString();
    }

    return input;

答案 7 :(得分:0)

替换代码:

var text = "example-123-example";
var pattern = @"-(\d+)-";
var replaced = Regex.ReplaceGroupValue(text, pattern, 1, "AA");

扩展类:

public static class RegexExtensions
{
    [Pure]
    public static string ReplaceGroupValue(this Regex source, string input, string groupName, string destinationValue)
    {
        return ReplaceGroupValue(
            source,
            input,
            m => m.Groups[groupName],
            p => destinationValue);
    }

    [Pure]
    public static string ReplaceGroupValue(this Regex source, string input, int groupIdx, string destinationValue)
    {
        return ReplaceGroupValue(
            source,
            input,
            m => m.Groups[groupIdx],
            p => destinationValue);
    }

    [Pure]
    public static string ReplaceGroupValue(this Regex source, string input, string groupName, Func<string, string> destinationValueSelector)
    {
        return ReplaceGroupValue(
            source,
            input,
            m => m.Groups[groupName],
            destinationValueSelector);
    }

    [Pure]
    public static string ReplaceGroupValue(this Regex source, string input, int groupIdx, Func<string, string> destinationValueSelector)
    {
        return ReplaceGroupValue(
            source,
            input,
            m => m.Groups[groupIdx],
            destinationValueSelector);
    }

    [Pure]
    private static string ReplaceGroupValue(
        Regex source,
        string input,
        Func<Match, Group> groupSelector,
        Func<string, string> destinationValueSelector)
    {
        var matchResult = source.Matches(input);

        if (matchResult.Count <= 0)
        {
            return input;
        }

        var text = input;

        foreach (var group in matchResult.OfType<Match>().Select(groupSelector).OrderByDescending(p => p.Index))
        {
            var begin = group.Index > 0 ? text.Substring(0, group.Index) : string.Empty;
            var end = group.Index + group.Length < text.Length
                ? text.Substring(group.Index + group.Length)
                : string.Empty;
            var destinationValue = destinationValueSelector.Invoke(group.Value);
            text = $"{begin}{destinationValue}{end}";
        }

        return text;
    }
}