[英]Inject variable into regular expression
So I am trying to certain values from a URL. Suppose I have the following URL:所以我正在尝试从 URL 获取某些值。假设我有以下 URL:
let url = "https://gk.example.com/my-path/to/some+more/multiple.variables/moreparams";
I am trying to extract the some+more
and multiple.variables
parts from the URL using a Regular Expression.我正在尝试使用正则表达式从 URL 中提取
some+more
和multiple.variables
部分。 I came up with the following expressions:我想出了以下表达式:
/(?<=/)([^/]*\+[^/]*)(?=/)/g
(for the +
separator) and /(?<=/)([^/]*\.[^/]*)(?=/)/g
(for the .
separator) /(?<=/)([^/]*\+[^/]*)(?=/)/g
(用于+
分隔符)和/(?<=/)([^/]*\.[^/]*)(?=/)/g
(用于.
分隔符)
results = url.match(/(?<=/)([^/]*\+[^/]*)(?=/)/g); // result: ['some+more']
results = url.match(/(?<=/)([^/]*\.[^/]*)(?=/)/g); // result: ['gk.example.com', 'multiple.variables']
This returns ['some+more']
and ['gk.example.com', 'multiple.variables']
, which is a result I can work with.这将返回
['some+more']
和['gk.example.com', 'multiple.variables']
,这是我可以使用的结果。 However, instead of using a if statement to switch between expressions, I would rather inject a variable into a generic regular expression.但是,我不想使用 if 语句在表达式之间切换,而是将变量注入通用正则表达式。 I tried the following (using backticks ( ` ) to be able to inject the variable:
我尝试了以下(使用反引号( ` )能够注入变量:
function getSplitUrl(sep, url) {
if (!url) url = window.location.href;
let regex = new RegExp('(?<=/)([^/]*'+sep+'[^/]*)(?=/)', `g`),
results = [];
results[0] = url.match(`(?<=/)([^/]*${sep}[^/]*)(?=/)`, `g`);
results[1] = regex.exec(url);
console.log('Regex 1: ', regex); // logs `Regex 1: /(?<=/)([^/]*${sep}[^/]*)(?=\/)/g`, where ${sep} is replaced by either \. or \+ (seemingly correct expression)
console.log(url, sep, results);
return null;
}
From the console.log(regex)
it seems that it is the correct regular expression but the result is still wrong.从
console.log(regex)
看似乎是正确的正则表达式,但结果仍然是错误的。 The result is now ['gk.example.com', 'gk.example.com']
.结果现在是
['gk.example.com', 'gk.example.com']
。
Am I missing something obvious here?我在这里遗漏了一些明显的东西吗?
Edit:编辑:
Somehow, url.match(regex)
returns a correct result, whereas regex.exec(url)
does not.不知何故,
url.match(regex)
返回了正确的结果,而regex.exec(url)
却没有。
Keep it simple and don't use regex, but rather the URL
API to parse urls:保持简单,不要使用正则表达式,而是使用
URL
API来解析 url:
const url = new URL("https://gk.example.com/my-path/to/some+more/multiple.variables/moreparams?limit=5&more=conf/fusion"); console.log(url.hostname); console.log(url.pathname) const parts = url.pathname.slice(1).split('/'); console.log(parts); const find = (substring) => parts.filter(p => p.includes(substring)); console.log(find('+')); console.log(find('.'));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.