[英]Regex .*? doesn't match everything
我正在嘗試制作一個適用於以下字符串的正則表達式
(?P<service>[az\-_]+)/(?<service2>[0-9]+)
(?P<stylesheet>[\/\s%\w\.\(\)\[\]\@_\-]+)/variations
我首先為#1嘗試了以下代碼,它按預期工作
測試 1: '(?P<service>[az\-_]+)/(?<service2>[0-9]+)'.replace(/\(.*?<(.*?)>.*?\)/g, '{$1}')
預期 Output : '{service}/{service2}'
結果 output :相同
但是,相同的模式不適用於#2。
測試 2: '(?P<stylesheet>[\/\s%\w\.\(\)\[\]\@_\-]+)/variations'.replace(/\(.*?<(.*?)>.*?\)/g, '{$1}')
預期 Output : {stylesheet}/variation
結果 Output : '{stylesheet}[]@_-]+)/variations'
它留下[]@_-]+)
部分。
.*?
不匹配[]@_-]+)
以及如何更改我的正則表達式以適用於兩個字符串?
您可以使用積極的前瞻來斷言右側的/
或字符串的末尾(?=\/|$)
:
\(.*?<([^<>]*)>.*?\)(?=\/|$)
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.