[英]Javascript regex match only words starting with a specific special character
I'm trying to match only words starting with # in javascript, for eg. 我试图在javascript中仅匹配以#开头的单词,例如。 in the following sample text, only #these should match. 在以下示例文本中,只有#these应该匹配。
I need to match only words like #these. 我只需匹配像#these这样的单词。 Ignore the ones like @#this , !#this and in#ignore. 忽略像@#this,!#this和#ignore中的那些。
The closer I got is here, 我越接近这里,
/(\B(#[a-z0-9])\w+)/gi
Ref: https://regex101.com/r/wU7sQ0/114 参考: https : //regex101.com/r/wU7sQ0/114
Use a whitespace boundary (?:^|\\s)
: 使用空白边界(?:^|\\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);
Details : 细节 :
(?:^|\\s)
- matches the start of string or whitespace (?:^|\\s)
- 匹配字符串或空格的开头 (#[a-z0-9]\\w*)
- Group 1 ( m[1]
): a #
, then an alphanumeric char followed with 0 or more word chars (letters, digits, _
symbols). (#[a-z0-9]\\w*)
- 组1( m[1]
): #
,然后是一个字母数字字符,后跟0个或多个字符(字母,数字, _
符号)。 See the regex demo , pay attention to what texts are captured , rather to the whole matches. 查看正则表达式演示 ,注意捕获的文本,而不是整个匹配。
Or trimming each match: 或修剪每场比赛:
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);
I little bit changed your regex to get what do you want. 我有点改变你的正则表达式来得到你想要的东西。
var p = "I need to match only words like #these. Ignore the ones like @#this , !#this and in#ignore."
[^@!a-z$]\#[a-z]+
That will be match only #these, you can exclude whatever you don't want by adding between first square bracket 这将只匹配#these,您可以通过在第一个方括号之间添加来排除您不想要的任何内容
you can try this, 你可以尝试这个,
txt = "I need to match only words like #these. Ignore the ones like @#this , !#this and in#ignore." console.log(/(^|\\s)(#+\\w+)/g.exec(txt))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.