Reputation: 321
I would like my code to find anywhere in the string that there is a number next to a letter and insert a space between the two.
I have several addresses that have no spaces and I need to insert spaces by separating out the numbers from the letters. For example:
123MainSt.Box123
Should be 123 Main St. Box 123
or
123Parkway134
should be: 123 Parkway 134
Here is where I started with my code but it was combing both numbers in the beginning....
Dim Digits() As String = Regex.Split(Address, "[^0-9]+")
'MsgBox(Digits.Count)
If Digits.Length > 2 Then
' For Each item As String In Digits
Dim Letters As String = Regex.Replace(Address, "(?:[0-9]+\.?[0-9]*|\.[0-9]+)", "")
rCell.Value = Digits(0) & Letters & Digits(1)
End If
If Digits.Length < 3 Then
If Address.Contains("th") Then
Else
Dim Part1 As String = Regex.Replace(Address, "[^0-9]+", "")
Dim Part2 As String = Regex.Replace(Address, "(?:[0-9]+\.?[0-9]*|\.[0-9]+)", "")
'MsgBox(Part1 & " " & Part2)
rCell.Value = Part1 & " " & Part2
End If
End If
Upvotes: 1
Views: 1667
Reputation: 627488
I would like my code to find anywhere in the string that there is a number next to a letter and insert a space between the two.
The regex you may use is
Regex.Replace(input, "(?<=\d)(?=\p{L})|(?<=\p{L})(?=\d)", " ")
The first alternative - (?<=\d)(?=\p{L})
- matches the location between a digit and a letter, and the second alternative - (?<=\p{L})(?=\d)
- matches a location between a letter and a digit.
Note that (?<=\p{L})
is a positive lookbehind that requires a letter before the current position and (?=\d)
is a positive lookahead that requires a digit after the current position. These are lookarounds that do not consume text, thus, you replace empty spaces with (= insert) a space.
Upvotes: 3
Reputation: 3863
Here's a quick function:
Private Function AddSpaces(ByVal input As String) As String
If input.Length < 2 Then Return input
Dim ReturnValue As String = String.Empty
Dim CurrentChar, NextChar As String
For x As Integer = 1 To input.Length
CurrentChar = Mid(input, x, 1)
NextChar = Mid(input, x + 1, 1)
ReturnValue &= CurrentChar
If (IsNumeric(CurrentChar) AndAlso (Not IsNumeric(NextChar))) OrElse
((Not IsNumeric(CurrentChar)) AndAlso IsNumeric(NextChar)) Then
ReturnValue &= " "
End If
Next
Return ReturnValue
End Function
Upvotes: 0