在执行Regex.Replace时如何使用命名捕获?我已经做到了这一点,它做了我想要的但不是我想要的方式:
[TestCase("First Second", "Second First")]
public void NumberedReplaceTest(string input, string expected)
{
Regex regex = new Regex("(?<firstMatch>First) (?<secondMatch>Second)");
Assert.IsTrue(regex.IsMatch(input));
string replace = regex.Replace(input, "$2 $1");
Assert.AreEqual(expected, replace);
}
Run Code Online (Sandbox Code Playgroud)
我希望将这两个单词与命名的捕获匹配,然后在执行替换时使用(命名)捕获.
我正在使用C#regex解析文本.我想为每场比赛只替换一个特定组.我在这里是怎么做的:
void Replace(){
string newText = Regex.Replace(File.ReadAllText(sourceFile), myRegex, Matcher, RegexOptions.Singleline);
//.......
}
void string Matcher(Match m){
// how do I replace m.Groups[2] with "replacedText"?
return ""; // I want to return m.Value with replaced m.Group[2]
}
Run Code Online (Sandbox Code Playgroud) 假设我有以下代码:
string input = "hello everyone, hullo anything";
string pattern = "h.llo [A-z]+";
string output = Regex.Replace(input,pattern,"world");
Run Code Online (Sandbox Code Playgroud)
(我已经尽力让它尽可能简单)
上面的代码输出是,"world, world"而我真正想要的是一种更改h.lloto之后的所有单词的方法world,并且我希望输出为"hello world, hullo world"
我一直在寻找一种方法来做到这一点,我进行了很多搜索并阅读了这篇文章:
但我并没有从中得到太多,而且我不确定这是否正是我想要的。
有什么办法吗?
想要以编程方式使用HTML标记格式化文章.在文章中找到模式并将其自身替换为每侧附加的标签的最佳方法是什么?更具体地说,我如何thematch在以下示例中传递匹配:
string formattedArticle
= Regex.Replace(article, "^\d.+", "<em>" + thematch + "</em>");
Run Code Online (Sandbox Code Playgroud) 我做了这行代码
mystring= Regex.Replace(mystring, @"\d+IEME", "E");
Run Code Online (Sandbox Code Playgroud)
但是因为我想保留这个号码而遇到了问题.喜欢7IEME替换7E