[英]Regex .*? doesn't match everything
I'm trying to make a regex that works for the following strings我正在尝试制作一个适用于以下字符串的正则表达式
(?P<service>[az\-_]+)/(?<service2>[0-9]+)
(?P<stylesheet>[\/\s%\w\.\(\)\[\]\@_\-]+)/variations
I first tried the following code for #1 and it worked as expected我首先为#1尝试了以下代码,它按预期工作
Test 1: '(?P<service>[az\-_]+)/(?<service2>[0-9]+)'.replace(/\(.*?<(.*?)>.*?\)/g, '{$1}')
测试 1: '(?P<service>[az\-_]+)/(?<service2>[0-9]+)'.replace(/\(.*?<(.*?)>.*?\)/g, '{$1}')
Expected Output : '{service}/{service2}'
预期 Output : '{service}/{service2}'
Result output : Same结果 output :相同
The same pattern doesn't work for #2 though.但是,相同的模式不适用于#2。
Test 2: '(?P<stylesheet>[\/\s%\w\.\(\)\[\]\@_\-]+)/variations'.replace(/\(.*?<(.*?)>.*?\)/g, '{$1}')
测试 2: '(?P<stylesheet>[\/\s%\w\.\(\)\[\]\@_\-]+)/variations'.replace(/\(.*?<(.*?)>.*?\)/g, '{$1}')
Expected Output : {stylesheet}/variation
预期 Output : {stylesheet}/variation
Result Output : '{stylesheet}[]@_-]+)/variations'
结果 Output : '{stylesheet}[]@_-]+)/variations'
It leaves []@_-]+)
part.它留下[]@_-]+)
部分。
How comes .*?
.*?
doesn't match []@_-]+)
and how do I change my regex to work for both strings?不匹配[]@_-]+)
以及如何更改我的正则表达式以适用于两个字符串?
You can assert either a /
to the right or the end of string (?=\/|$)
using a positive lookahead:您可以使用积极的前瞻来断言右侧的/
或字符串的末尾(?=\/|$)
:
\(.*?<([^<>]*)>.*?\)(?=\/|$)
const regex = /\(.*?<([^<>]*)>.*?\)(?=\/|$)/gm; [ `(?P<service>[az\\-_]+)/(?<service2>[0-9]+)`, `(?P<stylesheet>[\\/\\s%\\w\\.\\(\\)\\[\\]\\@_\\-]+)/variations` ].forEach(s => console.log(s.replace(regex, `{$1}`)) )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.