C#替换匹配开始结束的表达式 [英] C# Replace expression matching start end
问题描述
任何人都可以帮我在 C# 中的字符串中替换以startingChars"开头并以endingChars"结尾的任何字符串......类似这样的:
Can anyone help me do a replace in a string in C# of any any string starting with "startingChars" and ending with "endingChars"...something like that:
Regex.Replace(strToReplaceIn, "startingChars[anyNumberOfChars]endingChars", myFunction(anyNumberofChars));
其中 strStartingChars 和 strEndingChars 是两个字符串并且定义了 myFunction
where strStartingChars and strEndingChars are two strings and myFunction is defined
例如,如果开头是 "Hello, I need to replace startingCharsWITH_SOMETHINGendingChars, ...."
结果为: "Hello, I need to replace myFunctionResult("WITH_SOMETHING"), ..."
for example, if a starting is "Hello, I need to replace startingCharsWITH_SOMETHINGendingChars, ...."
the result to be: "Hello, I need to replace myFunctionResult("WITH_SOMETHING"), ..."
请让我知道有帮助的 Regex.Replace 表达式,问题不是找到匹配的表达式,而是替换...我该如何参考
Please, let me know the Regex.Replace expression that will help, the problem is not finding the matching expression, but the replacing...how can I refer to
anyNumberOfChars
在表达式的替换参数中?
in the replacement parameter of the expression?
我希望它足够清楚...谢谢
I hope it's clear enough...Thank you
推荐答案
您可以使用命名组轻松获取要替换的内容,并使用匹配评估器来构造替换字符串:
You can use a named group to easily get the contents to replace, and a match evaluator to construct the replacement string:
using System.Text.RegularExpressions;
static class Program {
static void Main(string[] args) {
string strToReplaceIn = "Hello, I need to replace startingCharsWITH_SOMETHINGendingChars, ....";
string replaced = Regex.Replace(strToReplaceIn, "startingChars(?<contents>.*?)endingChars", (match) => {
return "myFunctionResult(" + match.Groups["contents"].Value + ")";
});
}
}
一个 命名组((?<contents>.*?)
表达式中的位) 可以让您引用表达式的子部分,我认为这就是您所要求的.
或者,您可以使用一个简单的 group ,即只是括号之间的表达式,而没有 ?
部分:(.*)
.然后,您应该使用整数索引来引用它:
A named group (the (?<contents>.*?)
bit in the expression) is something that lets you refer to a subpart of the expression, which I think is what you are asking for.
Alternatively, you could use a simple group , i.e. just an expression between parenthesis, without the ?<name>
part: (.*)
. Then, you should refer to it with an integer index:
match.Groups[1].Value
(注:Groups[0] 代表整场比赛)
(Note: Groups[0] represents the whole match)
这篇关于C#替换匹配开始结束的表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!