Search code examples
regexpcresublimetext-snippet

Single regex that changes camel-case to dash-separated lowercase


I'm trying to write a SublimeText snippet for javascript import statements. I want the format the format to be like:

import MyFooBar from 'my-foo-bar';

The input to my regex is MyFooBar, and the output needs to be my-foo-bar. I found an answer that almost works in Regex - CamelCase to lower case with underscores:

Search for

((?<=.)[A-Z][a-zA-Z]*)|((?<=[a-zA-Z])\d+)

Replace with

-$1$2

The answer said to just use javascript's .toLowerCase() method for the lowercasing, but SublimeText snippets use perl, of which I have the briefest of knowledge. A quick search said that for lowercasing, I can use \L at the beginning of my replacement.

/((?<=.)[A-Z][a-zA-Z0-9]*)|((?<=[a-zA-Z])\d+)/\L-\1\2/g

This works on all but the first segment's character, so MyFooBar becomes My-foo-bar.

I thought maybe I could run two regexes in sequence, but either perl or Sublime doesn't recognize that.

Thoughts?

Edit:

When I say it uses perl, I just mean it uses a perl regex. As far as I can tell, I can't actually execute arbitrary code; I can only specify a regex that perl can execute.

Here's the full text of my snippet:

<snippet>
    <content><![CDATA[
import ${1:module} from '${2:./path/}${1/((?<=.)[A-Z][a-zA-Z0-9]*)|((?<=[a-zA-Z])\d+)/\L-\1\2/g}';
]]></content>
    <!-- Optional: Set a tabTrigger to define how to trigger the snippet -->
    <tabTrigger>import</tabTrigger>
    <!-- Optional: Set a scope to limit where the snippet will trigger -->
    <scope>source.js</scope>
</snippet>

Solution

  • I changed RegEx to something more useful and probably simple.

    ** Updated

    <snippet>
        <content><![CDATA[
    import ${1:module} from '${2:./path/}${1/(^[A-Z][a-z]+|[a-z])([A-Z])/\L\1-\2/g}';
    ]]></content>
        <!-- Optional: Set a tabTrigger to define how to trigger the snippet -->
        <tabTrigger>import</tabTrigger>
        <scope>source.js</scope>
    </snippet>