开发者

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 开发者_JAVA技巧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


(\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.


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


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

A PHP example to get the word blue.


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.


Another option:

(\w+)\\\w+$
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜