Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex Last occurrence?

Tags:

regex

path

Your negative lookahead solution would e.g. be this:

\\(?:.(?!\\))+$

See it here on Regexr


One that worked for me was:

.+(\\.+)$

Try it online!

Explanation:

.+     - any character except newline
(      - create a group
 \\.+   - match a backslash, and any characters after it
)      - end group
$      - this all has to happen at the end of the string

A negative look ahead is a correct answer, but it can be written more cleanly like:

(\\)(?!.*\\)

This looks for an occurrence of \ and then in a check that does not get matched, it looks for any number of characters followed by the character you don't want to see after it. Because it's negative, it only matches if it does not find a match.


You can try anchoring it to the end of the string, something like \\[^\\]*$. Though I'm not sure if one absolutely has to use regexp for the task.


What about this regex: \\[^\\]+$