正则表达式javascript搜索单词,但忽略几个单词

时间:2019-03-22 16:10:44

标签: javascript regex

下午好,

想知道是否可以搜索一个单词,但是在正则表达式中忽略与另一个单词相同的单词。

示例:         一:二:三:四:五:六:二三:九

答案:         一:二::四:五:六:二三:九

因此正则表达式只找到第一个单词Three,而忽略了Two Three。

我尝试过此正则表达式:

private teamMembers: Map<TeamMemberRole, TeamMemberName>;

constructor() {
    this.teamMembers = new Map<TeamMemberRole, TeamMemberName>();
    this.teamMembers.set('Manager', 'Kathy');
    this.teamMembers.set('Secretary', 'Bob');
    this.teamMembers.set('Engineer', 'Sally');
}

public getRole(memberName: TeamMemberName): TeamMemberRole {
    let teamMemberRole: TeamMemberRole;
    if (name) {
        this.teamMembers.forEach((name: TeamMemberName, role: TeamMemberRole) => {
            if (name === memberName) {
                teamMemberRole = role;
            }
        });
    }
    if (!teamMemberRole) {
        throw new Error('Not a recognized Team Member.');
    }
    return teamMemberRole;
}

public getName(role: TeamMemberRole): TeamMemberName {
    if (role) {
        return this.teamMembers.get(role);
    }
    throw new Error('Not a recognized Team Member.');
}

但是它不起作用,如果单词是两个,它确实起作用

我将不胜感激任何帮助或建议。谢谢

2 个答案:

答案 0 :(得分:1)

使用输入One : Two : Three : Four : Five : Six : Two Three : Nine

您可以忽略Two Three的情况

let str = 'One : Two : Three : Four : Five : Six : Two Three : Nine';
let re = /Two(?!\sThree)/g;
console.log(str.match(re));

答案 1 :(得分:1)

如果您正在寻找更通用的东西,我建议您使用纯粹的js方法:

let str = 'One : Two : Three : Four : Five : Six : Two Three : Nine';

let resp = str
  .split(' : ')
  .reduce((acc, ele) => acc.some(x => ele.search(x) > 0) ? acc : acc.concat(ele), [])
  .join(' : ');
  
console.log(resp);