Ugur Catak
Ugur Catak

Reputation: 191

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". How can I do that? Thanks.

Upvotes: 1

Views: 307

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627190

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.

If you need to replace any whitespace with -, replace m.Groups(1).Value.Replace(" ", "-") with Regex.Replace(m.Groups(1).Value, "\s", "-").

Upvotes: 2

Related Questions