简体   繁体   English

正则表达式捕获部分文本

[英]RegEx capture part of text

Could you help me, please! 请问你能帮帮我吗! I have a string like this: 我有一个像这样的字符串:

C:\\Temp dir\\Some one else\\File name.ext

I need to capture File name.ext But I can't understand how do it by regex. 我需要捕获File name.ext但是我不明白正则表达式是怎么做的。

When I trying to create regexp I can't understand how to capture only last symbol \\ and a text between them and . 当我尝试创建正则regexp我无法理解如何仅捕获最后一个符号\\以及它们之间的文本.

Hmm.. the following RegEx should do it: 嗯..下面的RegEx应该这样做:

\\[^\\]*\.

Depending on your language and environment, further escaping may be required for the backslashes and/or other characters. 根据您的语言和环境,反斜杠和/或其他字符可能需要进一步转义。

Try something like: 尝试类似:

[^\\]*\.\w+$

Use $ to anchor to end. 使用$锚定结束。

Breakdown explanation of the regex: 正则表达式的细分说明:

[^\\]*   Match the file name. (Any characters other than a \)
\.       Match the '.'.
\w+      Match the extension.
$        Anchor to end.

In response to comments on other questions, here is an alternative. 为了回应对其他问题的评论,这里是一种替代方法。

If you want to capture text between backslash 6 and 7 you can do the following: 如果要在反斜杠6和7之间捕获文本,可以执行以下操作:

(?:[^\\]*\\){6}([^\\]*)

Explanation: 说明:

(?: ){6}   A non-capturing group repeated 6 times
[^\\]*     Any number of characters other than backslash
\\.        Followed by backslash
([^\\]*)   capture all non backslash characters that follow

You can see this at work (with better explanation) at http://regex101.com/r/fP2cL7 您可以在http://regex101.com/r/fP2cL7上看到此文件(有更好的解释)

If you want a match between backslash 4 and 7, it would be 如果要在反斜杠4和7之间进行匹配,则应为

    (?:[^\\]*\\){4}((?:[^\\]*\\){2}[^\\]*)

As above but "don't do anything with the first four backslashes", then capture "no backslash followed by backslash twice, followed by no backslash one more time". 如上,但是“对前四个反斜杠不做任何事情”,然后捕获“不反斜杠,然后反斜杠两次,然后再不反斜杠一次”。 Which captures everything from backslash 4 to backslash 7 (without including the slashes at the end) 捕获从反斜杠4到反斜杠7的所有内容(不包括结尾的斜杠)

Using Powershell 使用Powershell

(gci $filepath).Name


Using Regex 使用正则表达式

(?!.*\\\\).*

This will match everything after the last slash \\ 这将匹配最后一个斜杠之后的所有内容\\

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM