I have some data cleansing task. I have a column which start from H6 and further down from their. The column contains data which was supposed to be in snake_case, but is not the case. The cell values are of the form:
I know there mat not be concrete algo to bring this all to snake_case, but I want to come up with code which will at least bring most cells to snake_case.
I tried VBA code to replace spaces with underscores and gets the index of underscores. Now I was thinking to make all character just after underscores to be lower case. Further I was thinking to replace sequence of two characters: first lower case and next in uppercase, say lC to l_c as I dont want CCC to get converted to c_c_c, but to ccc. But before moving further, I want to know if there can be simpler approach to this.
Here's one method that might do what you want:
Option Explicit
Function Snake_case(s As String) As String
Dim RE As Object
Const sPat As String = "([A-Za-z0-9]+)(?=[ _A-Z])[ _]?(\S+)"
Const sRepl As String = "$1_$2"
Dim v As Variant
Set RE = CreateObject("vbscript.regexp")
With RE
.Global = True
.ignorecase = False
.Pattern = sPat
v = Split(.Replace(s, sRepl), "_")
End With
v(0) = WorksheetFunction.Proper(v(0))
v(1) = LCase(v(1))
Snake_case = Join(v, "_")
End Function

And here is an explanation of the regex and replacement strings:
([A-Za-z0-9]+)(?=[ _A-Z])[ _]?(\S+)
Options: Case sensitive; ^$ match at line breaks
([A-Za-z0-9]+)
[A-Za-z0-9]+
+A-Za-z0-9(?=[ _A-Z])
[ _A-Z]
_A-Z[ _]?
?(\S+)
\S+
+$1_$2
$1_$2Created with RegexBuddy
Ron Rosenfeld solution didn't work for me. I used this one instead. Took similar on forum https://www.mrexcel.com/board/threads/camelcase-to-proper-case.381040/
Option Explicit
Function ToSnakeCase(txt As String) As String
'
' If cell A1 contains: SanFrancisco
' cell B1: =ToSnakeCase(A1)
' cell B1: San_Francisco
'
Dim Hold As String, i As Long
Hold = Left(txt, 1)
For i = 2 To Len(txt) Step 1
If Asc(Mid(txt, i, 1)) > 96 Then
Hold = Hold & Mid(txt, i, 1)
Else
Hold = Hold & "_" & Mid(txt, i, 1)
End If
Next i
ToSnakeCase = Hold
End Function
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With