2

目前,我使用:

变量:

 int recordCount = 5;
 Header = "Index"; // Can also be "Starting Index"

标题:

 Header = Header.Split(' ')[0] + " (" + recordCount + ")";

变化:

 Index (5)

至:

 Index (6)

当我想用新的 Header 替换 Header 时,我使用上面的方法,但问题是当我开始在其中使用多个单词时,Header它会删除 Header Name 的其余部分。即当它说Starting Index:它只显示Starting

我可以使用正则表达式来简单地查找括号之间的值并将其替换为另一个变量吗?

4

6 回答 6

6
Regex re = new Regex(@"\(\w+\)");
string input = "Starting Index: (12asd)";
string replacement = "12ddsa";
string result = re.Replace(input, replacement);

如果您需要执行更复杂的替换(即,如果替换取决于大括号之间的捕获值),则必须坚持使用Regex.Match方法

更新:Match事情很快就会变得丑陋:)

 Regex re = new Regex(@"^(.*)\((\w+)\)\s*$");
 string input = "Starting Index: (12)";
 var match = re.Match(input);

 string target = match.Groups[2].Value;
 //string replacement = target + "!!!!"; // general string operation
 int autoincremented = Convert.ToInt32(target) + 1; // if you want to autoincrement

 string result = String.Format("{0}: ({1})", match.Groups[1].Value, autoincremented);
于 2012-11-21T14:11:40.053 回答
1

如果您需要系统地替换其中的一些(并且算法需要原始值),请记住 Regex.Replace() 可以接受将返回替换值的方法。这是一个示例,它将增加括号中包含的所有整数:

string s1 = "Index (5) and another (45) and still one more (17)";

string regex = @"\((\d+)\)";

string replaced = Regex.Replace(s1,regex,m => "("+(Convert.ToInt32(m.Groups[1].Value)+1).ToString()+")");
// Result: Index (6) and another (46) and still one more (18)

该方法接受一个正则表达式匹配对象并返回一个替换字符串。我在这里使用了 lambda 方法,但是您的正则表达式和替换方法都可以根据需要变得复杂。

于 2012-11-21T15:00:51.193 回答
1

你也可以这样:

string sample = "Index (5) Starting Index(0) and Length (6)";
string content = Regex.Replace(sample, @"(?<=\()\d+(?=\))", m => (int.Parse(m.Value) + 1).ToString());

此模式将查找用圆括号括起来的任意数量的数字,并将推进到 1。

这里不需要附加额外的括号,因为它们在比赛期间没有被捕获。

于 2012-11-21T20:20:59.357 回答
0

你可以使用这个模式

\[\((\d+)\).*?\]

匹配括号之间的数字,然后您可以用您想要的任何数字替换该数字

var mg = Regex.Match( "Starting Index:(10)", @"\[\((\d+)\).*?\]");

if (mg.Success)
{
    var num = mg.Groups[1].Value; // num == 10
}

在那之后

headerString = headerString.Replace("10", "11");
于 2012-11-21T14:11:40.933 回答
0

\((\d+)\)这将更适合

并在这种情况下替换数字“asdq(wdq)wdqwd (12)”

于 2012-11-21T14:16:36.210 回答
0
int dynamicNumber = 6;

string pattern = string.Format("({0})", dynamicNumber);

string data = "My Header 6:";

Console.WriteLine (Regex.Replace(data,pattern, "!!!")); // My Header !!!:
于 2012-11-21T14:23:27.067 回答