简体   繁体   English

正则表达式:在起始分隔符和可选的结束分隔符之间捕获

[英]Regex: capture between starting delimiter and optional ending delimiter

With the following string: 使用以下字符串:

foo/:something/bar/:somethingelse

How can I capture something and somethingelse considering the optional / ending delimiter on the second case? 考虑到第二种情况下的可选/结束分隔符,我如何捕获something somethingelse

Using (?<=:)(.*?)(?=\\/) only returns something , which makes sense. 使用(?<=:)(.*?)(?=\\/)只返回something有意义的something

So I've tried (?<=:)(.*?)(?=\\/|$) but it doesn't return somethingelse either. 所以我试过(?<=:)(.*?)(?=\\/|$)但它也没有返回somethingelse

According to Regex101 this (?=\\/|$) means either / or end of the string, so in principle somethingelse should be captured. 根据Regex101,这个(?=\\/|$)表示字符串中的一个/或结尾,因此原则上应该捕获somethingelse字符串。

https://regex101.com/r/gU4uR9/2 https://regex101.com/r/gU4uR9/2

What am I missing? 我错过了什么?

As already pointed out by others, the JavaScript regex engine is somewhat crippled (and does not support lookbehinds). 正如其他人已经指出的那样,JavaScript正则表达式引擎有些瘫痪(并且不支持lookbehinds)。
The usual work-around is to match the things before (this consumes characters) and capture the desired substring in a group afterwards: 通常的解决方法是匹配之前的事物(这会消耗字符)并在之后捕获组中所需的子字符串:

\/:([^/]+)

See a demo on regex101.com . 请参阅regex101.com上的演示

In JS code, this would be: JS代码中,这将是:

var str = "foo/:something/bar/:somethingelse";
var re = /\/:([^/]+)/g;
var matches = str.match(re);

Thanks to @Wiktor for the clarification of nomenclature. 感谢@Wiktor澄清命名法。

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

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