简体   繁体   English

正则表达式匹配最后一个字符和字符串

[英]Regex to match between last character and string

I have a URL that looks as follows... 我有一个看起来如下的URL ...

/images/home/img/digits.png /images/home/img/digits.png

I need to use regex or some equivalent to get 'digits' from the URL. 我需要使用正则表达式或一些等价物从URL中获取“数字”。 I am using regex because the same code will be duplicated and the file names will always be different lengths. 我正在使用正则表达式,因为相同的代码将被复制,文件名将始终是不同的长度。

I've tried using regex and I get everything after the first / and before the .png, but I need everything after the last / and and before the .png. 我已经尝试过使用正则表达式,并且在第一个/之前和之后得到了所有内容。但是我需要在最后一个/之后和之前的所有内容.png。

Here is what I've been trying: 这是我一直在尝试的:

(?<=/)(.*)(?=.png)
"/images/home/img/digits.png".match(/\/([^\/]*)\.png/i)

回报

["/digits.png", "digits"]

You're really close. 你真的很亲密 (?<=/)([^/]*)(?=\\.png$) should work. (?<=/)([^/]*)(?=\\.png$)应该有效。

The three things I added do the following: 我添加的三件事做了以下事情:

  1. [^/]* matches any character(s) that don't include '/' , so the match can't inlcude any slashes. [^/]*匹配任何不包含'/'字符,因此匹配不能包含任何斜杠。
  2. The \\ before the .png stops the . .png之前的\\停止了. from matching any character. 从匹配任何角色。
  3. The $ anchors it to the end of the string. $将它锚定到字符串的末尾。

Also, if you're only looking to match the digits part and you don't care about the rest, you don't need the brackets around [^/]* because the lookahead and lookbehind quantifiers you're using aren't included in the match. 此外,如果您只想匹配数字部分并且您不关心其余部分,则不需要[^/]*周围的括号,因为您使用的前瞻和后视量词不包括在内在比赛中。 So in the above pattern, the only thing that will be returned will be what's matched by [^/]* . 所以在上面的模式中,唯一会被返回的东西是[^/]*匹配的东西。 This will either be found in the implicit group 0, or in Match.Value if you're using .NET. 如果您使用的是.NET,则可以在隐式组0中找到它,也可以在Match.ValueMatch.Value它。

To summarise all of that, what I would use is (?<=/)[^/]*(?=\\.png$) . 总结一下,我将使用的是(?<=/)[^/]*(?=\\.png$) It would also pay to add a case-insensitive flag if you want to also match "/images/home/img/digits.PNG" . 如果你想匹配"/images/home/img/digits.PNG" ,也可以添加一个不区分大小写的标志。

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

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