Regex to match and group up to first period and last slash

Viewed 157

I am working on creating a regular expression that matches and groups in the following way:

Example input: hello.world1/world2/index.js

Example desired regex grouping: [hello].[world1/world2]/[index.js]

Where anything NOT inside the brackets is ignored. I currently have this Regex: (^.*\.)(.*\/)(.*$) and is capturing the following:

current regex

Notice how group 1 includes the period and group 2 includes the last slash. Both which I don't want. Any help to correct this regex would be appreciated.

1 Answers

You need to take the literal chars out of the capturing groups:

^([^.]*)\.(.*)\/(.*)$

See the regex demo and the regex graph:

enter image description here

Details:

  • ^ - string start
  • ([^.]*) - any zero or more chars other than a . char as many as possible
  • \. - a dot
  • (.*) - Group 2: any zero or more chars other than line break chars, as many as possible
  • \/ - a / char
  • (.*) - Group 3: any zero or more chars other than line break chars, as many as possible
  • $ - string end.
Related