簡體   English   中英

如何在使用Regex.Replace方法時找到子字符串?

[英]How to get found substring while using Regex.Replace method?

我正在使用此代碼來替換索引中的所有找到的值:

int i = 0;
input = "FGS1=(B+A*10)+A*10+(C*10.5)";
Regex r = new Regex("([A-Z][A-Z\\d]*)");
bool f = false;
MatchEvaluator me = delegate(Match m)
{
  f = true;
  i++;
  return "i" + i.ToString();
};
do { f = false; input = r.Replace(input, me); } while (f);
//expected result: input == "i1=(i2+i3*10)+i4*10+(i5*10.5)"

但我必須以更復雜的方式做到這一點,因為我必須用已發現的價值做些什么。 例如:

MatchEvaluator me = delegate(Match m)
{
  foundValue = /*getting value*/;
  if (foundValue = "A") i--;
  f = true;
  i++;
  return "i" + i.ToString();
};

此代碼的預期結果: "i1=(i2+i2*10)+i2*10+(i3*10.5)"

您可以使用匹配對象中的Groups集合來獲取匹配的組。 第一項是整個匹配,因此第一組的值位於索引1處:

string foundValue = m.Groups[1].Value;
if (foundValue == "A") i--;

猜測你需要實現一個變量賦值,在其中為每個變量分配ix(其中x是遞增的數字),然后重用該值,如果它出現,我們可以編寫以下代碼來解決你的問題:

var identifiers = new Dictionary<string, string>();
int i = 0;
var input = "FGS1=(B+A*10)+A*10+(C*10.5)";
Regex r = new Regex("([A-Z][A-Z\\d]*)");
bool f = false;

MatchEvaluator me = delegate(Match m)
{
    var variableName = m.ToString();

    if(identifiers.ContainsKey(variableName)){
        return identifiers[variableName];
    }
    else {
        i++;
        var newVariableName = "i" + i.ToString();
        identifiers[variableName] = newVariableName;
        return newVariableName;
    }
};

input = r.Replace(input, me);
Console.WriteLine(input);

此代碼應打印:i1 =(i2 + i3 * 10)+ i3 * 10 +(i4 * 10.5)

你的問題應該由Guffa回答,只想分享我的替代方法來解決你的問題,使用.NET Regex的更多功能(如果我正確理解你的問題):

int i = 1;
string input = "FGS1=(B+A*10)+A*10+(C*10.5)";   
var lookUp = new Dictionary<string, string>();
var output = Regex.Replace(input, 
             "([A-Z][A-Z\\d]*)", 
             m => { 
                if(!lookUp.ContainsKey(m.Value))
                {           
                    lookUp[m.Value] = "i" + i++;            
                }
                return lookUp[m.Value]; 
            });
Console.WriteLine(output);      //i1=(i2+i3*10)+i3*10+(i4*10.5)

我使用字典來跟蹤重復的匹配

即使重復匹配與“A”不同,這也應該有效。 在您的原始解決方案中,它專門檢查“A”,這是非常脆弱的

暫無
暫無

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

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