开发者

Regex for formatting controlID to remove abbrev and space by capitals?

I am trying to write a regex that takes these examples:

tbZipCode

cbHavingLunch

rfvAssessment

tbAddress1

tbAddress12

And output:

Zip Code

Having Lunch开发者_JS百科

Assessment

Address 1

Address 12

My code:

Private Shared Function formatControlName(ByVal controlName As String) As String
    Dim newName As String = Nothing

    If controlName <> Nothing Then
        newName = Regex.Replace(controlName, "^[a-z]*|(([A-Z])|((?<=[A-Za-z])\d))", "$1").TrimStart()
    End If

    Return newName
End Function

I basically want to remove any of the string before the first capital/number (as that will be the control abbrev and isn't useful for people receiving this output) and then space it out based on whether it's a capital or the first number after a lowercase.

What's the right regex pattern?

Edited: The pattern above just removes the control abbrev, but doesn't add the spaces.


I'm no regex expert, but this one seems to work:

Private Shared Function formatControlName(ByVal controlName As String) As String


   Dim newName as string = _
   Regex.Replace(controlName, _
   "^[a-z]*|(([A-Z])|((?<=[A-Za-z])\d))", " $1").TrimStart


   Return newName
End Function

Note that in your original code, you need to return newName, not controlName to get the result of the regex.replace. Also, it looks like you are setting the newName string to nothing, then trying to make sure that it isn't nothing before executing the regex.replace?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜