简体   繁体   English

如何在VB.NET中捕获的regex子表达式中的所有空格替换为破折号?

[英]How can I replace all spaces into a dash in a captured subexpression of regex in VB.NET?

Here is my code: 这是我的代码:

regExp = New Regex("\[def\](.+?)\[\/def\]")
strTextToReplace = regExp.Replace(strTextToReplace, "<a href=""/$1"">$1</a>")

I want to replace all spaces with a dash in "$1". 我想用“ $ 1”中的破折号替换所有空格。 How can I do that? 我怎样才能做到这一点? Thanks. 谢谢。

You may use a match evaluator: 您可以使用匹配评估程序:

Dim rx = New Regex("(?s)\[def](.+?)\[/def]")
Dim result = rx.Replace(s, New MatchEvaluator(Function(m As Match)
         Return String.Format("<a href=""/{0}"">{0}</a>", m.Groups(1).Value.Replace(" ", "-"))
     End Function))

m is the Match object that is passed to the Regex.Replace method when a match occurs, and you replace all spaces with hyphens only in .Groups(1) (the first capturing group. m是发生匹配时传递给Regex.Replace方法的Match对象,并且仅在.Groups(1) (第一个捕获组.Groups(1)中用连字符替换所有空格。

If you need to replace any whitespace with - , replace m.Groups(1).Value.Replace(" ", "-") with Regex.Replace(m.Groups(1).Value, "\\s", "-") . 如果需要将任何空格替换为- ,请将m.Groups(1).Value.Replace(" ", "-")替换为Regex.Replace(m.Groups(1).Value, "\\s", "-")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM