在最后前进或后退斜杠之前的所有内容的正则表达式

时间:2022-05-31 21:19:20

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\

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

3 个解决方案

#1


39  

Try this: (Rubular)

试试这个:( 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.

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

#2


0  

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

^(。* [\\\ /])[^ \\\ /] * $

#3


0  

If you're using sed for example, you could do this to output everything before the last slash:

例如,如果您使用sed,则可以在最后一个斜杠之前输出所有内容:

echo "/home/me/documents/morestuff/before_last/last" | sed s:/[^/]*$::

It will output:

它将输出:

/home/me/documents/morestuff/before_last

#1


39  

Try this: (Rubular)

试试这个:( 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.

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

#2


0  

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

^(。* [\\\ /])[^ \\\ /] * $

#3


0  

If you're using sed for example, you could do this to output everything before the last slash:

例如,如果您使用sed,则可以在最后一个斜杠之前输出所有内容:

echo "/home/me/documents/morestuff/before_last/last" | sed s:/[^/]*$::

It will output:

它将输出:

/home/me/documents/morestuff/before_last