在最后一个正斜杠或反斜杠之前的所有内容的正则表达式 [英] Regex for everything before last forward or backward slash

查看:41
本文介绍了在最后一个正斜杠或反斜杠之前的所有内容的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个正则表达式来查找字符串中的所有内容,包括最后一个 \ 或/.

例如,c:\directory\file.txt 应该导致 c:\directory\

解决方案

试试这个:(Rubular)

/^(.*[\\\/])/

说明:

<前>^ 行/字符串的开始( 开始捕获组.* 贪婪地匹配任何字符[\\\/] 匹配反斜杠或正斜杠) 结束捕获组

由于.*的贪婪性,匹配的斜线将是最后一个.

如果您的语言支持(或需要)它,您可能希望对正则表达式使用与 / 不同的分隔符,这样您就不必转义正斜杠.

此外,如果您正在解析文件路径,您可能会发现您的语言已经有一个可以执行此操作的库.这比使用正则表达式要好.

I need a regex that will find everything in a string up to and including the last \ or /.

For example, c:\directory\file.txt should result in c:\directory\

解决方案

Try this: (Rubular)

/^(.*[\\\/])/

Explanation:

^      Start of line/string
(      Start capturing group
.*     Match any character greedily
[\\\/] Match a backslash or a forward slash
)      End the capturing group  

The matched slash will be the last one because of the greediness of the .*.

If your language supports (or requires) it, you may wish to use a different delimiter than / for the regular expression so that you don't have to escape the forward-slash.

Also, if you are parsing file paths you will probably find that your language already has a library that does this. This would be better than using a regular expression.

这篇关于在最后一个正斜杠或反斜杠之前的所有内容的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆