簡體   English   中英

在所有比賽中通過RegEx替換單個組

[英]Replace single group via RegEx in all matches

我有一個包含HTML元素的文本,其中超鏈接不包含URL,而是指向應打開的超鏈接的ID。 現在,我正在嘗試獲取所有這些ID並將其替換為新ID。 場景是,所有ID都已更改,並且我有一個詞典,其中包含“ oldId-> newID”,需要在文本中替換。

此輸入

Some text some text <a href = "##1234"> stuff stuff stuff <a href="##9999"> xxxx

有了這個字典映射

1234 -> 100025
9999 -> 100026

應該產生這個輸出

Some text some text <a href = "##100025"> stuff stuff stuff <a href="##100026"> xxxx

到目前為止,我有這個:

var textContent = "...";

var regex = new Regex(@"<\s*a\s+href\s*=\s*""##(?<RefId>\d+)""\s*\\?\s*>");
var matches = regex.Matches(textContent);

foreach (var match in matches.Cast<Match>())
{
    var id = -1;
    if (Int32.TryParse(match.Groups["RefId"].Value, out id))
    {
        int newId;
        // idDictionary contains the mapping from old id to new id
        if (idDictionary.TryGetValue(id, out newId))
        {
          // Now replace the id of the current match with the new id
        }
    }
}`

我現在如何更換ID?

只需在替換中使用回調即可。

regex.Replace(textContent, delegate(Match m) {
    int id = -1, newId;
    if (Int32.TryParse(m.Groups["RefId"].Value, out id)) {
        if (idDictionary.TryGetValue(id, out newId))
            return newId.ToString();
    }
    return m.Value; // if TryGetValue fails, return the match
});

不要用正則表達式解析HTML。

但是,如果必須,如果您要執行替換,請使用Replace方法

var updatedContent =  regex.Replace(textContent, match =>
    {
        var id = -1;
        if (Int32.TryParse(match.Groups["RefId"].Value, out id))
        {
            int newId;
            // idDictionary contains the mapping from old id to new id
            if (idDictionary.TryGetValue(id, out newId))
            {
                // Now replace the id of the current match with the new id
                return newId.ToString();
            }
        }

        // No change
        return match.Value;
    });

編輯:正如您所指出的,這將替換整個比賽 哎呦。

首先,更改您的正則表達式,以便您要替換的內容整個匹配項:

@"(?<=<\s*a\s+href\s*=\s*""##)(?<RefId>\d+)(?=""\s*\\?\s*>)"

這僅匹配一個數字字符串,但確保它前后都有HTML標記。

現在,它應該可以執行您想要的操作,但是為了整潔,您可以僅用\\d+ (因為您不再需要該組)替換(?<RefId>\\d+) ,然后將match.Groups["RefId"].Value與只是match.Value

除非您也從HTML中提取新的ID,否則我不明白為什么不能只使用直接String.Replace

var html = "Some text some text <a href = '##1234'> stuff stuff stuff <a href='##9999'> xxxx";
var mappings = new Dictionary<string, string>() 
{
    { "1234", "100025" },
    { "9999", "100026" },
    ...
};
foreach (var map in mappings) 
{
    html = html.Replace("##" + map.Key, "##" + map.Value);
}

小提琴

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM