0

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

Noitidart
  • 35,443
  • 37
  • 154
  • 323
  • 1
    Unfortunately, there's no way of doing this in a snippet, as you can't perform computational logic in them aside from what the regexes do. You'll need a plugin for this. – MattDMo Jan 04 '16 at 02:23
  • Aw darn, thansk so much Matt for the reply :) – Noitidart Jan 04 '16 at 09:30
  • 1
    No problem. It's a feature that would be really nice to have, just simple `if..then..else` kind of logic, but we get what we get :) – MattDMo Jan 04 '16 at 18:15
  • 1
    At any rate, do you know Python? It shouldn't be too hard to put together a plugin that does this. – MattDMo Jan 04 '16 at 18:16
  • Thanks very much @MattDMo for the work arounds, I actually don't know python im a javascript guy, but ill look for some simple examples. I did read a bunch of python ctypes. By chance do you have any small python script that enables similar functionality? I learn best from taking a related piece of work and tweaking it :) – Noitidart Jan 04 '16 at 19:48
  • 1
    I'll see if I can come up with something. – MattDMo Jan 04 '16 at 19:52
  • My sincerest gratitude! +1 for the thought even if you dont get time to. – Noitidart Jan 04 '16 at 20:34

1 Answers1

1

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')/});
r-stein
  • 4,627
  • 2
  • 16
  • 27