我有一些需要处理的示例字符串
string1 = "_Wondrous item, common (requires attunement by a wizard or cleric)_"
string2 = "_Weapon (glaive), rare (requires attunement)_"
string3 = "_Wondrous item, common_"我想把它们分解成以下几个
group1 = {
type: "Wonderous item";
rarity: "common";
attune: True
class: "wizard or cleric"
}
group2 = {
type: "Weapon (glaive)";
rarity: "rare";
attune : True
}
group3 = {
type: "Wondrous item"
rarity: "common"
attune: False
}我目前的正则表达式是混乱的,可能效率很低,但它只分解了第一个。
regex = /_(?<type>[^:]*),\s(?<rarity>[^:]*)\s\((?<attune>[^:]+)by a(?<class>[^:]*)\)_/U增列细节
发布于 2021-11-17 00:56:47
若要使用模式获取3行的所有组,请执行以下操作:
_(?<type>[^:]*?),\s+(?<rarity>[^:]*?)(?:\s+\((?<attune>[^:]+?)\s*(?:by\s+a\s+(?<class>[^:]*?))?\))?__(?<type>[^:]*?)匹配_,组类型匹配除:以外的任何字符,\s匹配,和空格字符(?<rarity>[^:]*?)组的稀有性匹配除:以外的任何字符(?:非捕获群\s\(匹配空格char和((?<attune>[^:]+?)\s*组调谐器匹配除:以外的任何字符(?:by a\s+(?<class>[^:]*?))?也可以选择匹配by a和group类,它们匹配除:之外的任何字符(非贪婪)。\)匹配))?_使外部组可选,并匹配_看一个regex演示。
使用groups属性if 支持,您可以检查值并相应地更新对象。
const regex = /_(?<type>[^:]*?),\s+(?<rarity>[^:]*?)(?:\s+\((?<attune>[^:]+?)\s*(?:by\s+a\s+(?<class>[^:]*?))?\))?_/;
[
"_Wondrous item, common (requires attunement by a wizard or cleric)_",
"_Weapon (glaive), rare (requires attunement)_",
"_Wondrous item, common_"
].forEach(s => {
const m = s.match(regex);
if (m) {
if (m.groups.class === undefined) {
delete m.groups.class;
}
m.groups.attune = m.groups.attune === undefined ? false : true;
console.log(m.groups)
}
});
注意到,在您的模式中,您希望阻止在否定字符类中匹配:,但是示例数据中没有:。
对于第一个被否定的字符类,您可以将其更改为与逗号不匹配,而对于其他类,则排除匹配括号以获得相同的结果。
这样,并不是所有的量词都必须是不贪婪的,它可以防止一些不必要的回溯。
_(?<type>[^,]*),\s(?<rarity>[^:()]*)(?:\s\((?<attune>[^()]+?)\s*(?:by a\s+(?<class>[^()]*))?\))?_看另一个regex演示。
https://stackoverflow.com/questions/69997659
复制相似问题