How to identify a regular expression

This question already has an answer here:

  • Is there a regular expression to detect a valid regular expression? 8 answers

  • Assuming you want to target a source (ex: an article) and want to check which words are used most commonly in that source:

    Assume the whole block of texts in the articles are in one string, assigned to variable "str":

    // Will be used to track word counting
    const arrWords = [];
    // Target string
    const str = 'fsdf this is the article fsdf we are targeting';
    // We split each word in one array
    const arrStr = str.trim().split(' ');
    
    // Lets iterate over the words
    const iterate = arrStr.forEach(word => {
      // if a new word, lets track it by pushing to arrWords
      if (!arrWords.includes(word)) {
        arrWords.push({ word: word, count: 1 });
      } else {
        // if the word is being tracked, and we come across the same word, increase the property "count" by 1
        const indexOfTrackedWord = arrWords.indexOf(word);
        arrWords[indexOfTrackedWord].count++;
      }
    });
    
    // Once that forEach function is done, you now have an array of objects that look like this for each word: 
    arrWords: [
      {
        word: 'fsdf',
        count: 2
      },
      {
        word: 'this',
        count: 1
      },
      // etc etc for the other words in the string
    ];
    

    Now you can just console.log(arrWords) to look at the results!

    链接地址: http://www.djcxy.com/p/76736.html

    上一篇: 评估正则表达式的正则表达式

    下一篇: 如何识别正则表达式