Javascript正则表达式匹配字符串中以“#”开头的任何单词

编程入门 行业动态 更新时间:2024-10-27 02:24:52
本文介绍了Javascript正则表达式匹配字符串中以“#”开头的任何单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我是正则表达式的新手。我试图在一个不包含换行符的字符串中匹配以'#'开头的任何单词(内容已经在换行符处拆分)。

I'm very new at regex. I'm trying to match any word that starts with '#' in a string that contains no newlines (content was already split at newlines).

示例(不工作) :

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' ]

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

I am trying to match any instance of '#', and grab the thing right after it, so long as there is at least one letter, number, or symbol following it. A space or a newline should end the match. The '#' should either start the string or be preceded by spaces.

这个PHP解决方案看起来不错,但它使用的是向后看的类型的功能,我不这样做知道JS正则表达式是否: 正则表达式保留/匹配任何以某个字符开头的单词

This PHP solution seems good, but it uses a look backwards type of functionality that I don't know if JS regex has: regexp keep/match any word that starts with a certain character

推荐答案

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

检查 此演示 。

Check this demo.

更多推荐

Javascript正则表达式匹配字符串中以“#”开头的任何单词

本文发布于:2023-11-06 16:11:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1564170.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   中以   单词   开头   正则表达式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!