regex 正则表达式匹配单词,如果它前面是另一个单词

pgx2nnw8  于 2022-12-05  发布在  其他
关注(0)|答案(1)|浏览(236)

我试图编写一个正则表达式,以匹配一个单词的所有示例,只要该行的第一个字符是//。
下面的例子...

//foo bar
//bar foo
Something else with the word foo

前两行是单词foo的匹配项,但第三行没有匹配项,因为单词foo之前没有//字符。
到目前为止,我只设法匹配的话,无论它是在前面的//使用这个...

\bfoo\b

如果单词紧跟在//字符之后,则使用OR匹配该单词。

#*\/\/foo
zf9nrax1

zf9nrax11#

使用以下示例:

var data = `//foo bar
//bar foo
Something else with the word foo
//foo test more foo
//not has with defaul word - not match
    `;
    function getAllInstancesOfAWord(word) {
      const regex = new RegExp(`^\/\/(.*${word}.*)`, 'gm');
      console.log(regex);
      // Use regex match function
      const array = data.match(regex);
      // console.log(array);
      for (let i=0;i<array.length; i++){
        console.log(`Found instance word contain "${word}" begin with "//" = ${array[i].substring(2)}`);
      }
    }
    getAllInstancesOfAWord('foo');
    getAllInstancesOfAWord('not');

注意事项:
^\/\/(.*foo.*):获取包含单词“foo”的示例字符串,以“//"开始。
string.substring(2):获取从索引2开始到结束的所有字符,表示排除“//"。
告诉我,我是不是错了你的想法,多知识多力量,对不对!

相关问题