Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A regex to split a file path

Tags:

regex

I want to create a regex to split a path as shown in the following scheme:

Path:        c:\foo\bar\baz.txt
Root name:   c:
Parent path: c:\foo\bar
Filename:    baz.txt
Stem:        baz
Extension:   txt

Here is what I have. The problem is that it doesn't work when I have a filename without an extension:

^(([aA-zZ]:)\\(?:[^:]+))\\(([^\\]+)\.([^\.]+))$

I can change it to

^(([aA-zZ]:)\\(?:[^:]+))\\(([^\\]+)(\.([^\.]+))?)$

but it doesn't split a filename to a stem and an extension.

like image 725
john c. j. Avatar asked Jun 28 '26 04:06

john c. j.


1 Answers

You may use this regex with a lazy quantifier and an optional group:

^(([a-zA-Z]:)(?:\\[^:]+)?)\\(([^\\\n]+?)(?:\.([^.\n]+))?)$

RegEx Demo

It is important to make ([^\\]+?) a lazy match to avoid it matching too much when next non-capture group i.e. (?:\.([^.\n]+))? is an optional match.

like image 103
anubhava Avatar answered Jun 29 '26 18:06

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!