Bogdan Craciun
Bogdan Craciun

Reputation: 177

How to get the previous word with regex?

I have a path like this one:

C:\Development.TFS\Examn\R4-branch\Web\OrganisationManager\themes\blue\css

And I need a regex to get the word "blue" out of there. I tried, but didn't find a solution yet. It's practically getting the word before the last word from that string. Please help, thank you

Upvotes: 3

Views: 5509

Answers (5)

Tim Pietzcker
Tim Pietzcker

Reputation: 336428

(\w+)\W+\w+$

matches the second-to-last word, captures it into backreference no. 1, then matches one or more non-word characters, then the last word and then EOL.

If you don't really want actual words but path elements to match (even if they contain non-word characters), then

([^\\:]+)\\[^\\]+$

might do a better job.

Edit: Added a : to the "second-to-last-word group" so the regex can handle relative paths, too.

Upvotes: 6

Alix Axel
Alix Axel

Reputation: 154643

Another option:

(\w+)\\\w+$

Upvotes: 0

Rorick
Rorick

Reputation: 8953

You should find this pattern in string: ([\w\s.-]+)\\[\w\s.-]+$. The first group will containg word 'blue' in your case. Exact syntax of regex and accessing groups depends on your programming language.

Upvotes: 0

Sam Holder
Sam Holder

Reputation: 32944

can't you simply split the string using the character '\' then get the splitResult[splitResult.Count-1]?

you could always replace '\' by the path separator in your environment, for more consistent results

Upvotes: 1

Marco
Marco

Reputation: 2336

if (eregi('themes\\([a-z].+)\\css', $subject)) { # Successful match } else { # Match attempt failed }

A PHP example to get the word blue.

Upvotes: 0

Related Questions