Search code examples
regexsublimetext2sublimetext-snippet

Sublime Snippet, if no regex match use "null" string


I'm trying to write a snippet. For this post I super simplified it. If I run it on this selection:

arg1

the snippet should output:

doFunc('arg1', 'null');

if I run it on this selection:

arg1, arg2

the snippet should output

doFunc('arg1', arg2);

I can't figure out how to use null string if no regex match is found. This is what I have so far:

 doFunc('${SELECTION/([^,]+)(,.*)?/\1/}', ${SELECTION/([^,]+)(,.*)?/\2/});

So the problem here is ${SELECTION/([^,]+)(,.*)?/\2/} I want to do like a tertiary so like \2 ? \2 : null is this possible?

Thanks


Solution

  • Sublime Text Snippets use the Boost library, which actually supports ternary operators in the format part. Hence you can just write (?{2}(\2):'null') like a ternary operator.

    If you change your snippet to this it will have the specified behavior:

    doFunc(${SELECTION/^([^,]+)(?:,\s*(.*))?/'\1', (?{2}(\2):'null')/});