简体   繁体   English

如何捕获可选模式之间的任何模式组?

[英]How to capture any pattern groups between optional patterns?

What would be the best approach to match an optional pattern at the end of a string, after an any pattern, using Regex in Javascript?在任何模式之后,使用 Javascript 中的正则表达式匹配字符串末尾的可选模式的最佳方法是什么? Is there a way to make an optional pattern inclusive when it comes at the end of the string and after an any pattern?有没有办法在字符串末尾和任何模式之后使可选模式包含在内?

My Regex:我的正则表达式:

'{any:any}'.match(/\{?(.+):(.+)\}?/);

Current Result:当前结果:

['{any:any}', 'any', 'any}', index: 0, input: '{any:any}', groups: undefined]

Expected Result:预期结果:

['{any:any}', 'any', 'any', index: 0, input: '{any:any}', groups: undefined]

If you want to keep the curly's optional, you can use 2 capture groups in combination with a negated character class:如果你想保持 curly 的可选,你可以使用 2 个捕获组与否定字符 class 组合:

{?([^{}:]+):([^{}:]+)}?

Regex demo正则表达式演示

 console.log('{any:any}'.match(/{?([^{}:]+):([^{}:]+)}?/));

If you don't want to cross newlines, you can exclude them:如果您不想跨越换行符,可以排除它们:

{?([^{}:\n]+):([^{}:\n]+)}?

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

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