3

一致した正規表現文字列の一部だけを置き換えるにはどうすればよいですか? のようないくつかの括弧にあるいくつかの文字列を見つける必要があります< >。この例では、23 文字を照合し、そのうち 3 文字だけを置き換える必要があります。

string input = "<tag abc=\"hello world\"> abc=\"whatever\"</tag>";
string output = Regex.Replace(result, ???, "def");
// wanted output: <tag def="hello world"> abc="whatever"</tag>

したがって、 を検索abcする<tag abc="hello world">か、検索<tag abc="hello world">して置き換える必要がありますabc。正規表現または C# はそれを許可しますか? また、問題を別の方法で解決したとしても、大きな文字列を一致させて、その一部だけを置き換えることは可能ですか?

4

3 に答える 3

0

名前付きグループを使用した作業サンプル:

string input = @"<tag abc=""hello world""> abc=whatever</tag>";
Regex regex = new Regex(@"<(?<Tag>\w+)\s+(?<Attr>\w+)=.*?>.*?</\k<Tag>>");
string output = regex.Replace(input, match => 
{
    var attr = match.Groups["Attr"];
    var value = match.Value;
    var left = value.Substring(0, attr.Index);
    var right = value.Substring(attr.Index + attr.Length);
    return left + attr.Value.Replace("abc", "def") + right;
});
于 2013-11-06T11:16:20.317 に答える