gpt4 book ai didi

javascript - 正则表达式 - 收集强制前缀和可选组之间的字符

转载 作者:行者123 更新时间:2023-11-28 17:54:22 25 4
gpt4 key购买 nike

我正在 JavaScript 中创建正则表达式来查找所有出现的组,所有这些都是可选的。

我现在已经收集了可选组(感谢 @wiktor-stribiżew )。缺少的事情是在 new- 前缀和第一个出现的组之间收集字符。

输入:

new-rooms-3-area-50
new-poland-warsaw-rooms-3-area-50-bar
new-some-important-location-rooms-3-asdads-anything-area-50-uiop
new-another-location-area-50-else

请求的输出:

["rooms-3", "area-50"]
["poland-warsaw", "rooms-3", "area-50"]
["some-important-location", "rooms-3", "area-50"]
["another-location", "area-50"]

我现在有了

new-(?:.*?(rooms-\d+))?.*?(area-\d+)

正则表达式。我认为在 new-rooms|area 之间收集 .* 可能是愚蠢的解决方案。

在线演示:https://regex101.com/r/QvmYN0/5

注意:我创建了两个单独的问题,因为它指的是两个单独的问题。我希望将来有人遇到类似的问题。

最佳答案

我认为最好按如下步骤进行拆分:

// Split by \n to work with each line
getArrays = input => input.split`\n`.map(x => {

// Split by your desired delimiters:
// -dashes which has "area" or "rooms" in front
return x.split(/-(?=area-|rooms-)/g).map(y => {

// remove the "new-" from start or anything in front the numbers
return y.replace(/^new-|\D+$/, '');

// make sure you don't have empty cases
}).filter(y => y);

});

var txt = `new-rooms-3-area-50
new-poland-warsaw-rooms-3-area-50-bar
new-some-important-location-rooms-3-asdads-anything-area-50-uiop
new-another-location-area-50-else`;

console.log(getArrays(txt));

编辑:上面的代码返回请求的输出。但是,我认为您应该需要一组模型:

// initial state of your model
getModel = () => ({
new: '',
area: 0,
rooms: 0,
});

// the function that will return the array of models:
getModels = input => input.split`\n`.map(line => {
var model = getModel();

// set delimiters:
var delimiters = new RegExp(
'-(?=(?:' + Object.keys(model).join`|` + ')-)', 'g');

// set the properties of your model:
line.split(delimiters).forEach(item => {

// remove non-digits after the last digit:
item.replace(/(\d)\D+$/, '$1')

// set each matched property:
.replace(/^([^-]+)-(.*)/,
(whole_match, key, val) => model[key] = val);
});

return model;
});

var txt = `new-rooms-3-area-50
new-poland-warsaw-rooms-3-area-50-bar
new-some-important-location-rooms-3-asdads-anything-area-50-uiop
new-another-location-area-50-else`;

console.log(getModels(txt));

关于javascript - 正则表达式 - 收集强制前缀和可选组之间的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44787443/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com