I’m trying to write a Visual Studio Code snippet that converts Pascal case to lowercase with spaces. I’m almost there:
${1/([A-Z]*)([A-Z][a-z]+)/$1 ${2:/downcase} /g}
Group 1 matches acronyms and group 2 matches capitalized words.
So if the placeholder were MyUIDTest
, the expected result would be my UID test
. But currently I get my UID test
(notice the spaces on either side).
How do I only add a space after group 1 if group 1 has a match? And how do I remove the space at the end of the line?
2
Answers
According to the docs,
${1:+ }
means "insert a space iff group 1 is captured":Since
$2
and$3
are mutually exclusive, using them both always results in only one being actually inserted.PascalCase
pascal case
MyUIDTest
my UID test
FoOBaR
fo O ba R
A more precise (and verbose) version would be (note that
b
needs to be escaped again when written in a JSON string:"\b"
):I’m using
TM_SELECTED_TEXT
here, but you might want to change that depending on your needs.I think to remove the space at the end of the line,you can simply add a newline character at the end of the replacement pattern, and when you use the snippet with the placeholder "MyUIDTest", it should correctly produce "my UID test" without any extra spaces.
also to add a space after group 1 only if it has a match, you can use a conditional statement in the replacement pattern