gpt4 book ai didi

javascript - 确保仅当第一个元素不存在时正则表达式才移动到第二个 OR 元素

转载 作者:行者123 更新时间:2023-12-02 06:26:50 25 4
gpt4 key购买 nike

我正在尝试匹配字符串上的某个单词,只有当它不存在时我才想使用 OR | 运算符匹配另一个单词....但匹配是忽略...我如何确保该行为有效:

const str = 'Soraka is an ambulance 911'
const regex = RegExp('('+'911'+'|'+'soraka'+')','i')
console.log(str.match(regex)[0]) // should get 911 instead

最佳答案

911 出现在字符串的后面,而 Soraka 出现在前面,正则表达式引擎逐个字符地迭代,所以 Soraka 得到首先匹配,即使它位于交替的右侧。

一种选择是在捕获的先行中匹配 Soraka911,然后使用正则表达式匹配对象,在两组之间交替以获得不是 undefined:

const check = (str) => {
const regex = /^(?=.*(911)|.*(Soraka))/;
const match = str.match(regex);
console.log(match[1] || match[2]);
};

check('Soraka is an ambulance 911');
check('foo 911');
check('foo Soraka');

关于javascript - 确保仅当第一个元素不存在时正则表达式才移动到第二个 OR 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57751609/

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