Get the last instance of a pattern

I need help in a regular expression that will get the last instance of a pattern in a single line.

The lines in question are written in the following pattern (separated by slashes):

/this/is/how/it/looks/

In the example above, I am expecting to get looks as the output.

Note that the lines are not uniform and can contain less or more strings than the example.

/it/can/be/shorter/
/it/can/also/be/longer/than/most/lines/

For the above lines, I expect to get shorter and lines respectively.

Answers


/([^/]*)/$

is the regex you need.

Explanation:

/      # Match a slash
(      # Start capturing group number 1
 [^/]* # Match any number of characters except slashes
)      # End capturing group number 1
/      # Match a slash
$      # Match the position at the end of the string

Test it live on regex101.com.


If you use Powershell, you can write something like this:

$line.TrimEnd("/").Split("/")[-1]

If you are sure there is always a trailing slash, you can skip the trim step with:

$line.Split("/")[-2]

You can use \w+(?=/$), this will match the last name in each line

Explanation

\w+ any set of 'word characters a-z, A-Z, 0-9 and _.

(?=/$) positive lookahead for '/' followed by the end of the string.


Abstracted pattern: ( This works for a space, you can replace the first 'literal character' with anything you'd like )

----/----

(\ .[^\ ]+)(?=$)

Cheers


Need Your Help

Microsoft.SqlServer.Dac issue

powershell nuget teamcity octopus-deploy dacpac

I'm trying to deploy an MVC Project along with a database using Octopus. When the step for deploying the database is hit I'm getting the following error: