我正在尝试仅匹配以散列(var newDate = new Date(year, month, day);
)开头,后跟连字符(#
)开头的文本。
示例文本:-
我已经尝试过了,但这不是最好的。有什么办法可以使Regex更加精确?
#stack-overflow-questions
答案 0 :(得分:2)
可能先查找#
,然后查找一个或多个\w+-
(如果允许#stack
,则查找零个或多个),然后查找一个或多个\w
:
const rex = /#(?:\w+-)+\w+/;
实时示例:
const rex = /#(?:\w+-)+\w+/;
console.log(rex.exec("blah blah #stack-overflow-questions blah blah")); // Finds it
console.log(rex.exec("blah blah #stack blah blah")); // null
答案 1 :(得分:1)
下面应该完成这项工作。
^#[a-z\-]+
答案 2 :(得分:0)
var str = "blah blah #stack-overflow-questions #stack-overflow-questiosss blah blah";
var pat = /#[\w+-]{2,}/g;
var result = str.match(pat);
找到2个匹配项
{2,}过去不仅捕获“-”,而且仍然可以捕获“-”