【问题标题】:Javascript Regex match any word that starts with '#' in a stringJavascript 正则表达式匹配字符串中以“#”开头的任何单词
【发布时间】:2012-11-25 18:45:14
【问题描述】:

我对正则表达式很陌生。我正在尝试匹配不包含换行符的字符串中以“#”开头的任何单词(内容已在换行符处拆分)。

示例(不工作):

var string = "#iPhone should be able to compl#te and #delete items"
var matches = string.match(/(?=[\s*#])\w+/g)
// Want matches to contain [ 'iPhone', 'delete' ]

我正在尝试匹配“#”的任何实例,并抓住它后面的东西,只要它后面至少有一个字母、数字或符号。空格或换行符应该结束匹配。 '#' 应该以字符串开头或以空格开头。

这个 PHP 解决方案看起来不错,但它使用了向后看类型的功能,我不知道 JS 正则表达式是否有: regexp keep/match any word that starts with a certain character

【问题讨论】:

    标签: javascript regex


    【解决方案1】:
    var re = /(?:^|\W)#(\w+)(?!\w)/g, match, matches = [];
    while (match = re.exec(s)) {
      matches.push(match[1]);
    }
    

    检查this demo

    let s = "#hallo, this is a test #john #doe",
      re = /(?:^|\W)#(\w+)(?!\w)/g,
      match, matches = [];
    
    while (match = re.exec(s)) {
      matches.push(match[1]);
    }
    
    console.log(matches);

    【讨论】:

    • 编辑后的版本返回每个标签前的“#”:“Grocery #Shopping #list”.match(/(?:^|\W)#(\w+)(?!\w)/ g) ["#Shopping", "#list"]
    • @SimpleAsCouldBe - 您从我的答案中获取了一个正则表达式模式并使用了match,但这不是我的答案。我的代码与 #1 组一起使用以获得您想要的结果。请参阅我的答案中的演示链接以查看结果...
    • 哦,聪明。所以这取决于 .exec 返回匹配的方式,对吧?有点酷
    • @SimpleAsCouldBe - 查看文档以了解更多信息:developer.mozilla.org/en-US/docs/JavaScript/Reference/…
    【解决方案2】:

    试试这个:

    var matches = string.match(/#\w+/g);
    

    let string = "#iPhone should be able to compl#te and #delete items",
      matches = string.match(/#\w+/g);
    
    console.log(matches);

    【讨论】:

    • 我的错。我不知道你不想要#。
    • 这也会在单词的任何地方提取#,而不仅仅是单词的开头。
    【解决方案3】:

    您实际上也需要匹配哈希。现在,您正在寻找跟随 position 的单词字符,该位置紧跟几个非单词字符之一。这失败了,原因很明显。试试这个:

    string.match(/(?=[\s*#])[\s*#]\w+/g)
    

    当然,前瞻现在是多余的,所以你不妨去掉它:

    string.match(/(^|\s)#(\w+)/g).map(function(v){return v.trim().substring(1);})
    

    这将返回所需的:[ 'iPhone', 'delete' ]

    这是一个演示:http://jsfiddle.net/w3cCU/1/

    【讨论】:

    • 第二个示例中不需要捕获组。
    • 这会返回哈希,然后是子字符串。如果我们无论如何都必须对它进行子字符串化,为什么不使用这个呢? "杂货#Shopping #list".match(/#\w+/g).map(function(v){return v.substring(1);})
    • 这对于嵌入了# 的单词会失败(例如:“Don't #find this#one but only #this”)
    • @TedHopp 实际上不想抢'#',如果它是嵌入的
    • @SimpleAsCouldBe 这是最简单的正则表达式。我向你保证,我不需要扯掉 vaidik。无论如何,这里的关键部分是数组映射。
    猜你喜欢
    • 1970-01-01
    • 2010-11-17
    • 1970-01-01
    • 1970-01-01
    • 2012-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-23
    相关资源
    最近更新 更多