Sublime Forum

[Solved] [Help] Sublime regex replacement (snippet)

#1

Hi everyone,
I’m playing with sublime snippets.

I want to get “s” or “es” from FILE NAME using regex. This is my regex

class ${1}${TM_FILENAME/([a-zA-Z0-9])+([^(es_)|s_)]{1})//}Controller < ApplicationController
end

but I can’t get “s” or “es” only. anyone can help me?
eg:
customers_controller.rb -> should be return “s”
branches_controller.rb -> should be return “es”

thank for read.

0 Likes

#2
class ${1}${TM_FILENAME/^.*?(e?s)_.*$/$1/}Controller < ApplicationController
end.
  • ^ begin at start of filename
  • .*? match everything lazily
  • (e?s) optionally match e, match s, and put into capture group 1
  • _ underscore
  • .* match everything
  • $ end at end of filename
  • /$1/ replace everything that matched with capture group 1
2 Likes

#3

omg. thank you. I don’t think It’s so simple. thank you so much.

0 Likes

#4

Hi @kingkeith, Thank you again for your help. I built my own regex base on your instruction.

class ${1:${TM_FILENAME/([a-zA-Z]+)_?([a-zA-Z]+)?(s_controller\.rb)/\u\1\u\2/g}}sController < ApplicationController

It working well in cases: ([] = auto select text)
customers_controller.rb -> [Customer]sController
shipping_lists_controller.rb -> [ShippingListsController]

but it’s wrong when controller name end with es
branches_controller.rb -> [Branche]sController
It should be [Branch]esController

Any recommendation for me pls?

Thanks.

0 Likes

#5

I don’t entirely understand what you are trying to do.

If you want to get the first letter of the filename capitalized, along with the first letter after every underscore, you can use the following:

class ${1:${TM_FILENAME/(?:^|_)([a-z])|\.rb|(^$)/\u\1(?2:Controller)/g}} < ApplicationController
end.
  • (?:^|_) non capture group, start of string or _
  • followed by ([a-z]) capture group 1, lower case a-z
  • |\.rb or .rb
  • |(^$) or capture group 2, no filename (i.e. file not saved yet)

replace with:

  • \u\1 upper case capture group 1
    • in the .rb case, capture group 1 will be empty, and therefore will be replaced with nothing
  • (?2:Controller) if capture group 2 matched, insert the text Controller

File name customers_controller.rb becomes CustomersController, shipping_lists_controller.rb becomes ShippingListsController, branches_controller.rb becomes BranchesController, and an unsaved file will just become Controller.

Does that help?

1 Like

#7

I written a regex base on your regex.
Thank you very very very much.

0 Likes