Add an underscore in front of each lowercase letter followed by a lowercase

I am trying to add an underscore before each uppercase letter followed by a lower case. Here is an example:

cases <- c("XrefAcctnoAcctID", "NewXref1AcctID", "NewXref2AcctID", "ClientNo")

I have it:

[1] "XrefAcctnoAcctID" "NewXref1AcctID"  
[3] "NewXref2AcctID"   "ClientNo"     

And I want to have this:

"xref_acctno_acct_id" 
"new_xref1_acct_id"   
"new_xref2_acct_id"    
"client_no" 

I can go this far:

> tolower(gsub("([a-z])([A-Z])", "\\1_\\2", cases))
[1] "xref_acctno_acct_id" "new_xref1acct_id"   
[3] "new_xref2acct_id"    "client_no" 

But it "new_xref1acct_id" "new_xref2acct_id"does not reflect what I want.

+4
source share
1 answer

We can use regular expressions to match patterns that show a lowercase letter or number followed by an uppercase letter, and replace it with _

tolower(gsub("(?<=[a-z0-9])(?=[A-Z])", "_", cases, perl = TRUE))
#[1] "xref_acctno_acct_id" "new_xref1_acct_id"   "new_xref2_acct_id"  
#[4] "client_no"  

, , backreference , _

tolower(gsub("([a-z1-9])([A-Z])", "\\1_\\2", cases))
#[1] "xref_acctno_acct_id" "new_xref1_acct_id"   "new_xref2_acct_id"  
#[4] "client_no"       
+7

Source: https://habr.com/ru/post/1676176/


All Articles