如何使用正则表达式从状态为“通知”或“无库存”的字符串中删除项目
Posted
技术标签:
【中文标题】如何使用正则表达式从状态为“通知”或“无库存”的字符串中删除项目【英文标题】:How do I remove items from a string which have status "notify" or "not in stock" using regexp 【发布时间】:2021-07-24 11:57:05 【问题描述】:我正在努力制作一个正则表达式来删除状态为“通知”或“无库存”的项目
item1 120usd not in stock item2 150usd in stock item3 100usd notify item4 12usd in stock item5 25usd not in stock item6 250usd notify item7 50usd in stock item8 30sud in stock item9 5usd notify item10 5usd notify
以下正则表达式将匹配所有项目
.*?(notify|not in stock|in stock)
我试图从正则表达式中删除“in stock”,但随后所有分组都“混乱”了。
https://regex101.com/r/KyEg6k/1
感谢所有帮助:)
【问题讨论】:
【参考方案1】:一种选择可能是匹配您不想要的内容并在一个组中捕获您想要保留的内容。
要不跨越 in stock
或 not in stock
或 notify
,您可以使用带有负前瞻的 tempered greedy token。
\bin stock\b|(?:\s+|^)((?:(?!\b(?:notify|not in stock|in stock)\b).)+\b(?:notify|not in stock)\b)
\bin stock\b
在单词边界之间匹配 in stock
以防止部分匹配
|
或者
(?:\s+|^)
匹配 1+ 个空格字符或断言字符串的开头也匹配第一个单词
(
捕获group 1(在示例代码中由m[1]
引用)
(?:
钢化点的非捕获组
(?!\b(?:notify|not in stock|in stock)\b).
负前瞻,不直接在右侧断言任何替代方案。如果是这样,请使用 .
匹配任何字符
)+
关闭群组并重复1次以上
\b(?:notify|not in stock)\b
匹配单词边界之间的备选方案之一
)
关闭第一组
Regex demo
const str = "item1 120usd not in stock item2 150usd in stock item3 100usd notify item4 12usd in stock item5 25usd not in stock item6 250usd notify item7 50usd in stock item8 30sud in stock item9 5usd notify item10 5usd notify"
const regex = /\bin stock\b|(?:\s+|^)((?:(?!\b(?:notify|not in stock|in stock)\b).)+\b(?:notify|not in stock)\b)/g;
Array.from(str.matchAll(regex), m =>
if (m[1])
console.log(m[1]);
);
【讨论】:
太棒了 :) 感谢您的帮助和时间。一件小事......在正则表达式演示中 - 文本“库存”显示为 match2、match4、match7 和 match8。是否可以排除这些? @mocet 那是你不想要的匹配。你想要的是第 1 组,如记录第 1 组值的演示中所示。 你在浏览器中使用这个吗? javascript 对lookbehinds 的支持有限。 是的,我通过 chrome 扩展 (pageprobe) 在浏览器 (chrome) 中使用它,只有两列用于放入正则表达式,第二列用于替换匹配的值。 这正是我想要的。你们好棒!!非常感谢!以上是关于如何使用正则表达式从状态为“通知”或“无库存”的字符串中删除项目的主要内容,如果未能解决你的问题,请参考以下文章