如何在JavaScript中为特殊条件设置正则表达式?

如何在JavaScript中为特殊条件设置正则表达式?,javascript,regex,unicode,Javascript,Regex,Unicode,我需要为以下条件编写正则表达式模式的帮助: const subStr = postText.split(/(?=[\s:#,+/][a-zA-Z\d]+)(#+\w{2,})/gm); const result = _.filter(subStr, word => word.startsWith('#')).map(hashTag => hashTag.substr(1)) || []; Hashtag字符的限制 长度 您只需在单词前添加一个#即可将其作为标签。然而,由于Twe

我需要为以下条件编写正则表达式模式的帮助:

const subStr = postText.split(/(?=[\s:#,+/][a-zA-Z\d]+)(#+\w{2,})/gm);

const result = _.filter(subStr, word => word.startsWith('#')).map(hashTag => hashTag.substr(1)) || [];
Hashtag字符的限制 长度

  • 您只需在单词前添加一个#即可将其作为标签。然而,由于Tweet的长度仅限于140个字符以下,因此最好的hashtag是由单个单词或几个字母组成的。推特专家建议将关键字限制在6个字符以下

  • 在关键字中只使用数字和字母。您可以使用下划线,但出于美观考虑,请谨慎使用。连字符和破折号不起作用

  • 没有空间

    hashtag不支持空格。因此,如果你用的是两个单词,请跳过空格。例如,跟踪美国选举的标签被标记为#USelection,而不是$US election

  • 没有特殊字符

    hashtag只与#符号一起使用。特殊字符如“!,$,%,^,&,*,+,.”将不起作用。Twitter识别出英镑符号,然后将标签转换成可点击的链接

  • hashtag可以以数字开头

  • hashtag可以是任何语言

  • 标签可以是表情符号或符号

我是这样想的,但不包括最后两个条件:

const subStr = postText.split(/(?=[\s:#,+/][a-zA-Z\d]+)(#+\w{2,})/gm);

const result = _.filter(subStr, word => word.startsWith('#')).map(hashTag => hashTag.substr(1)) || [];
编辑: 示例:如果我有:

const postText = "#hello12#123 #hi #£hihi #This is #Assuming the characters that are not allowed in a hashtag are 
!$%^&*+.
(the ones you mentioned) and
,
(based on your example), you can use the following regex pattern:

/#[^\s!$%^&*+.,#]+/gm

const postText=“#hello12#123#hi#hi#hi#这是#假设hashtag中不允许的字符是
!$%^&*+。
(您提到的)和
(基于您的示例),您可以使用以下正则表达式模式:

function getHashTags(postText) {
  const regex = /#[^\s!$%^&*+.,£#]+/gm;
  const selectedHashTag = [];
  const subStr = postText.split(' ');
  const checkHashTag = _.filter(subStr, word => word.startsWith('#') || word.includes('#'));

  checkHashTag.map((hashTags) => {
    if (hashTags.match(regex)) {
      hashTags.match(regex).map(hashTag => selectedHashTag.push(hashTag.substr(1)));
    }
    return true;
  });
  return selectedHashTag;
}

注意:要排除更多字符,您可以像我上面所做的那样将它们添加到字符类中。显然,您不能仅仅因为希望支持其他Unicode符号和表情符号而依赖字母数字字符

JavaScript代码示例:

const regex=/#[^\s!$%^&*+,#]+/gm;

const str=“#hello12#123#hi#hi#hi#hi#这是#这是一个可能的解决方案,没有
,而
对我有效,感谢模式:


简单一点,
^\S+$
会有什么问题?@Tim Biegeleisen它只是返回我想要的确切的
文本check@Nafis你希望/期望它返回什么?@Ahmed Abdelhameed我编辑了问题谢谢语气,我使用了你的模式,它对我有效。我已经把你的答案写成了
答案
,而且
很有用