1

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.

6
  • java\\/(.+) -> i think you can try this use the value of captured group split it with / and replace by . Commented Dec 1, 2018 at 7:06
  • thanks that gave me a direction.. now with ${TM_DIRECTORY/.*[\\/]java\\/(.*[\\/].*)$/$1/} i can capture the group but was not able to do a transformation on captured group i.e com/mdmssa/controller has to be transformed to com.mdmssa.controller Any idea on that.. Commented Dec 1, 2018 at 11:05
  • Now you can simply replace the / with . using replace method Commented Dec 1, 2018 at 11:26
  • Try path.replaceAll(".+/(\\w+)/(\\w+)/(\\w+$)", "$1.$2.$3"); On the example path you give, it returns com.mdmssa.controller Commented Dec 1, 2018 at 15:41
  • Did something like ${TM_DIRECTORY/.*[\\/]java\\/(.*[\\/].*)$/${1/[\\]/\./}/} and it doesn't work.. and regex in path.replaceAll(".+/(\\w+)/(\\w+)/(\\w+$)", "$1.$2.$3") will work in most of my projects only drawback it is limited to 3 level of directory.. Commented Dec 2, 2018 at 8:01

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.