我试图在javascript中仅匹配以#开头的单词,例如.在以下示例文本中,只有#these应该匹配.
我只需匹配像#these这样的单词.忽略像@#this,!#this和#ignore中的那些.
我越接近这里,
/(\B(#[a-z0-9])\w+)/gi
Run Code Online (Sandbox Code Playgroud)
使用空格边界(?:^|\s):
var rx = /(?:^|\s)(#[a-z0-9]\w*)/gi;
var s = "I need to match only words like #these. \nIgnore the ones like @#this , !#this and in#ignore.";
var m, res=[];
while (m = rx.exec(s)) {
res.push(m[1]);
}
console.log(res);Run Code Online (Sandbox Code Playgroud)
详细资料:
(?:^|\s) -匹配字符串或空格的开头(#[a-z0-9]\w*)-第1组(m[1]):a #,然后是字母数字字符,后跟0个或多个单词字符(字母,数字,_符号)。查看正则表达式演示,注意捕获了哪些文本,而不是整个匹配项。
或修剪每个匹配项:
var rx = /(?:^|\s)(#[a-z0-9]\w*)/gi;
var s = "I need to match only words like #these. \nIgnore the ones like @#this , !#this and in#ignore.";
var results = s.match(rx).map(function(x) {return x.trim();}); // ES5
// var results = s.match(rx).map(x => x.trim()); // ES6
console.log(results);Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2421 次 |
| 最近记录: |