Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex extract string after the second "." dot character at the end of a string

I want to extract the second "file extension" of a file name so:

/Users/path/my-path/super.lol.wtf/main.config.js

What I need is:

.config.js

What would be totally awesome if I got an array with 2 strings in return:

var output = ['main', '.config.js'];

What I have tried:

^(\d+\.\d+\.)

But that ain't working.

Thanks

like image 323
randomKek Avatar asked Dec 16 '15 00:12

randomKek


1 Answers

You could use the following:

([^\/.\s]+)(\.[^\/\s]+)$

Example Here

  • ([^\/.\s]+) - Capturing group excluding the characters / and . literally as well as any white space character(s) one or more times.

  • (\.[^\/\s]+) - Similar to the expression above; capturing group starting with the . character literally; excluding the characters / and . literally as well as any white space character(s) one or more times.

  • $ - End of a line


Alternatively, you could also use the following:

(?:.*\/|^)([^\/.\s]+)(\.[^\/\s]+)$

Example Here

  • (?:.*\/|^) - Same as the expression above, except this will narrow the match down to reduce the number of steps. It's a non-capturing group that will either match the beginning of the line or at the / character.

The first expression is shorter, but the second one has better performance.

Both expressions would match the following:

['main', '.config.js']

In each of the following:

/Users/path/my-path/some.other.ext/main.config.js
some.other.ext/main.config.js
main.config.js
like image 159
Josh Crozier Avatar answered Sep 18 '22 00:09

Josh Crozier