从无#号的字符串中提取所有的hashtag

3
我将从类似这样的字符串中提取标签:
const mystring = 'huehue #arebaba,saas #ole #cool asdsad #aaa';
const hashtags = mystring.match(/#\w+/g) || [];
console.log(hashtags);

输出结果为:
['#arebaba', '#ole', '#cool', '#aaa']

我的正则表达式应该怎么写才能匹配以下内容:
['arebaba', 'ole', 'cool', 'aaa']

我不想使用map函数!


2
阅读有关正则表达式捕获组的内容。http://www.regular-expressions.info/brackets.html - Domino
3个回答

6

const mystring = 'huehue #arebaba,saas #ole #cool asdsad #aaa';
var regexp = /#(\w+)/g;
var match = regexp.exec(mystring);
while (match != null){
  console.log(match[1])
  match = regexp.exec(mystring)
} 

编辑代码可以缩短。但是,解决问题的不是你的正则表达式,而是选择正确的方法。

var mystring = 'huehue #arebaba,saas #ole #cool asdsad #aaa',
    match;
var regexp = /#(\w+)/g;    
while (match = regexp.exec(mystring))
  console.log(match[1]);


这个可以解决问题,但我不确定如何适应我的用例。在你的示例中,我的两行代码变成了七行。我只需要更改我的正则表达式,但不确定应该怎么改。 - user7308733
你有没有使用原型(prototype)的需求? - Marc Lambrichs

2
你已经匹配了多个子字符串,并且知道前面有一个#,所以只需将其删除即可:

const mystring = 'huehue #arebaba,saas #ole #cool asdsad #aaa';
const hashtags = mystring.match(/#\w+/g).map(x => x.substr(1)) || [];
console.log(hashtags);


指定在问题中:我不想使用map函数。 - Marc Lambrichs
@mlambrichs 是的,但这不是为了 OP,而是为了那些想要使用它的人。这个答案是一个社区维基答案。不使用 .map 的要求是“人为的”,听起来像是一项学校任务,而不是现实生活中的任务。 - Wiktor Stribiżew
我目前正在使用地图,但我想跳过这一步,直接提取没有#的标签。 - user7308733
1
@IbnClaudius。您没有使用 map 发布您的代码。因此,这里是答案,以防其他用户想要使用它。这是一个社区维基回答。 - Wiktor Stribiżew

0

您可以使用正向预查选项:

(?<=...)确保给定的模式将匹配,以表达式中的当前位置结束。该模式必须具有固定的宽度。不消耗任何字符。

例如,给定字符串“foobar”,正则表达式(?<=foo)bar只会匹配bar

或在此情况下(创建单词标记数组):

const mystring = 'huehue #arebaba,saas #ole #cool asdsad #aaa';
const hashtags = mystring.match(/(?<=#)\w+/g) || [];
// ["arebaba","ole","cool","aaa"];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接