[英]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? 我究竟做错了什么?
The issue with your code is your opening and closing slashes are part of your capture group. 代码的问题在于,您的开始和结尾斜杠是捕获组的一部分。
/1/2/test/
/1/2/test/
/\\/(\\[^\\/\\]*?)(?=\\/)/g
/\\/(\\[^\\/\\]*?)(?=\\/)/g
/
match characters must be escaped (according to regex101.com), which is why the cleaner [/]
wasn't used. /
匹配字符转义(根据regex101.com),这就是为什么未使用更干净的[/]
原因。 If you're only after the last match (ie, test
), you don't need the positive lookahead: 如果您只是在最后一场比赛之后(例如
test
),则不需要正向前行:
/\/([^\/]*?)\/$/
Match: 比赛:
/
" /
”的字符
/
" and then the end of string $
/
”,然后是字符串$
的末尾 Code: 码:
([^/]*)/$
Get the text in group(1)
获取
group(1)
的文本
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.