简体   繁体   English

试图弄清楚如何在正斜杠之间捕获文本

[英]Trying to figure out how to capture text between slashes regex

I have a regex 我有一个正则表达式

/([/<=][^/]*[/=?])$/g

I'm trying to capture text between the last slashes in a file path 我正在尝试捕获文件路径中最后一个斜杠之间的文本

/1/2/test/

but this regex matches " /test/ " instead of just test . 但是此正则表达式匹配“ /test/ ”,而不仅仅是test What am I doing wrong? 我究竟做错了什么?

You need to use lookaround assertions. 您需要使用环视断言。

(?<=\/)[^\/]*(?=\/[^\/]*$)

DEMO 演示

or 要么

Use the below regex and then grab the string you want from group index 1. 使用下面的正则表达式,然后从组索引1中获取所需的字符串。

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

The issue with your code is your opening and closing slashes are part of your capture group. 代码的问题在于,您的开始和结尾斜杠是捕获组的一部分。

Demo 演示版

  • text: /1/2/test/ 文字: /1/2/test/
  • regex: /\\/(\\[^\\/\\]*?)(?=\\/)/g 正则表达式: /\\/(\\[^\\/\\]*?)(?=\\/)/g
  • captures a list of three: "1", "2", "test" 捕获三个列表:“ 1”,“ 2”,“ test”
  • The language you're using affects the results. 您使用的语言会影响结果。 For instance, JavaScript might not have certain lookarounds, or may actually capture something in a non-capture group. 例如,JavaScript可能没有某些外观,或者可能实际上捕获了非捕获组中的某些内容。 However, the above should work as intended. 但是,以上应按预期工作。 In PHP, all / match characters must be escaped (according to regex101.com), which is why the cleaner [/] wasn't used. 在PHP中,必须将所有/匹配字符转义(根据regex101.com),这就是为什么未使用更干净的[/]原因。

If you're only after the last match (ie, test ), you don't need the positive lookahead: 如果您只是在最后一场比赛之后(例如test ),则不需要正向前行:

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

The easy way 简单的方法

Match: 比赛:

  1. every character that is not a " / " 每个不是“ / ”的字符
    • Get what was matched here. 在这里获取匹配的内容。 This is done by creating a backreference , ie: put inside parenthesis. 这是通过创建反向引用来完成的,即:放在括号内。
  2. followed by " / " and then the end of string $ 后跟“ / ”,然后是字符串$的末尾

Code: 码:

([^/]*)/$

Get the text in group(1) 获取group(1)的文本


Harder to read, only if you want to avoid groups 仅当您要避免分组时才更难阅读

Match exactly the same as before, except now we're telling the regex engine not to consume characters when trying to match (2). 匹配与以前完全相同,除了现在我们告诉正则表达式引擎在尝试匹配时不要消耗字符(2)。 This is done with a lookahead : (?= ) . 这是通过先行完成的: (?= )

Code: 码:

[^/]*(?=/$)

Get what is returned by the match object. 获取匹配对象返回的内容。

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

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