
Help with Regex.Replace pls...
Ok this is how I solved this problem, to let others benefit from the
solution...
Public Function FormatSePhoneNumber(ByVal strPhoneNumber As String) As
String
Dim objRegEx As Regex 'For pattern matching using regular
expression.
'MatchEvaluator delegate. An event handler that fires when an
"OnMatch event" occurs.
Dim objMatchEval As New MatchEvaluator(AddressOf MatchHandler)
Try
Return objRegEx.Replace(strPhoneNumber,
"(?<=-(?:\d{2}|\d{4}|\d{6}))(\d)", objMatchEval)
Catch ex As Exception
'If any exceptions are thrown.
MsgBox(ex.ToString, MsgBoxStyle.Critical, "Error")
Return strPhoneNumber 'No changes.
End Try
End Function
Private Function MatchHandler(ByVal objMatch As Match) As String
Try
Return " " & objMatch.Groups(1).Value 'Add a space before the
matched group.
Catch ex As Exception
'If any exceptions are thrown.
MsgBox(ex.ToString, MsgBoxStyle.Critical, "Error")
Return objMatch.Groups(1).Value 'No changes.
End Try
End Function
--
Regards
Ali Eghtebas Sweden
Quote:
> Hi,
> I have some numbers validated like this:
> ^\d{2,4}-[1-9]\d{4}(\d{0,3}$
> How can I using the replace method add a space between each pair of digits
> after the - sign?
> Like this: "##-## ## #" or "##-## ## ##" or
> "##-## ## ## #" or "##-## ## ## ##" etc.
> Using the code below I can do that but if group 5 or 6 are not matched and
> extra " " is always added to the end of the number e.g. "##-## ## # ".
> objRegEx.Replace(strNumber,
"^(\d{2,4}-[1-9]\d)(\d\d)(\d)(\d?)(\d?)(\d?)$",
Quote:
> "$1 $2 $3$4 $5$6"))
> There should be a much better way of doing this using regular expression
> replace, but I don't know how...
> --
> Thanks in advance
> Ali Eghtebas Sweden