目前,我使用:
变量:
int recordCount = 5;
Header = "Index"; // Can also be "Starting Index"标题:
Header = Header.Split(' ')[0] + " (" + recordCount + ")";更改:
Index (5)至:
Index (6)当我想用一个新的标题替换标题时,我使用上面的方法,但问题是当我开始在Header中使用多个单词时,它会删除标题名称的其余部分。也就是说,当它显示Starting Index:时,它只显示Starting。
我可以使用正则表达式简单地查找括号中的值并将其替换为另一个变量吗?
发布于 2012-11-21 22:11:40
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-21 23:00:51
如果您需要系统地替换其中的许多值(并且算法需要原始值),那么请记住,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-22 04:20:59
你也可以这样做:
string sample = "Index (5) Starting Index(0) and Length (6)";
string content = Regex.Replace(sample, @"(?<=\()\d+(?=\))", m => (int.Parse(m.Value) + 1).ToString());此模式将查找用圆括号括起的任意数量的数字,并将前进到1。
这里不需要附加额外的括号,因为它们不是在匹配过程中捕获的。
https://stackoverflow.com/questions/13495009
复制相似问题