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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With