Search code examples
regexcode-snippets

Regex with capturing group for vs code snippets


I am trying to have a VS code snippets.For generating java class.I am terrible with regex. As explained in here followed the instruction.

what i am trying is to extract the package name from my project path /home/bspl/Projects/SpringBoot/mdmssa/src/main/java/com/mdmssa/controller
which should be like

com.mdmssa.controller

the keyword here is java which will remain same in every project. Till now i came up with this following another thread in stackoverflow "${TM_FILEPATH/.*[\\/](.*[\\/].*)$/$1/}" Help would be much appreciated.


Solution

  • This one should work

    ${TM_DIRECTORY/.+java\\/|([^\\/]+)|(\\/)/$1${2:+.}/g}
    

    With global flag we have 3 groups that transform

    1. .+java\\/ - everything before and including last java/ transforms to empty string
    2. ([^\\/]+) - names between / after java/ doesn't transform
    3. (\\/) - / transforms to . through :+ which transforms capture if it is present