使用正则表达式捕获字符串的第一个字符,同时忽略"the "和"a "



我有一个Javascript中的音乐艺术家对象数组。我试图构建一个正则表达式来选择以选定字母开头的艺术家。然而,我需要排除"和&;a &;在每个艺术家名称字符串中,同时仍然考虑字符串其余部分的开始字符。

到目前为止,这是我得到的最接近的:

/(?!^the |^a )b${indexCharacter}?/i

我还没有实现${indexCharacter},只是专注于在"The Rolling Stones"的测试用例中使用^r。来测试一下。

这样就可以了,我想我应该在字符串"the Mighty Mighty boston"上测试一下。它抓住了第一和第二"M"我已经很接近了,我只是不知道如何在第一时间阻止它。我想用问号就可以了

肯定有办法做到这一点。帮助吗?

下面是一个基于您的描述的测试用例:

const artists = [
{ name: 'The Rolling Stones', stars: 5 },
{ name: 'Santana', stars: 5 },
{ name: 'Queen', stars: 4 },
{ name: 'The Beatles', stars: 3 },
{ name: 'Jimi Hendrix', stars: 5 },
{ name: 'Joe Cocker', stars: 3 },
{ name: 'Pink Floyd', stars: 5 },
{ name: 'Rammstein', stars: 5 },
{ name: 'The Clash', stars: 2 },
{ name: 'The Cure', stars: 2 },
{ name: 'The Damned', stars: 3 },
{ name: 'Tool', stars: 2 },
{ name: 'A Perfect Circle', stars: 1 },
{ name: 'Alice Cooper', stars: 4 },
];
function findArtists(query) {
return artists.filter(a => {
let re = new RegExp('^' + query.toLowerCase());
return re.test(a.name.toLowerCase().replace(/^((a|the)s)/, ''));
});
}
[ 'a', 'j', 'ji', 'r', 't' ].forEach(query => {
let result = findArtists(query);
console.log('- query: ' + query + ' => ' + JSON.stringify(result));
});

输出:

- query: a => [{"name":"Alice Cooper","stars":4}]
- query: j => [{"name":"Jimi Hendrix","stars":5},{"name":"Joe Cocker","stars":3}]
- query: ji => [{"name":"Jimi Hendrix","stars":5}]
- query: r => [{"name":"The Rolling Stones","stars":5},{"name":"Rammstein","stars":5}]
- query: t => [{"name":"Tool","stars":2}]

正则表达式new RegExp('^((a|the)\s)?' + query.toLowerCase())的解释

  • ^-字符串
  • 起始
  • (-启动组1(您可以将其变为非捕获(?:...)组)
    • (a|the)- group forathe
    • \s-后跟空格(由于字符串导致的双反斜杠)
  • )?-结束组1,?使其可选
  • 后面跟着查询词,小写
  • 提示:如果查询是用户指定的,则转义查询中的特殊正则表达式字符

你不需要一个复杂的正则表达式,你可以去掉你不想要的前缀,然后得到第一个字母:

function getArtistFirstLetter(artist) {
return artist
.replace(new RegExp('/the |a /i'), '')
.charAt(0)
}

虽然前面有空格,但这是可行的

/(?=[^a|the]).+/i

实际上没有必要用问号

/[^a|the].+/i

相关内容

最新更新