2017-06-01 103 views
1

是否存在能够确定字符串是普通单词还是正则表达式的模式?或者是否有JavaScript工具可以完成它?如何识别正则表达式

一个正则表达式可以从一个字符串创建,并且通常具有以下形式:[a-zA-z] * \ d?

而一个常见的词可能是:'猫','狗'等我想知道一个字符串的值是否是一个正则表达式而不是一个普通的词。

换句话说,我可以写一个正则表达式来识别正则表达式吗?

+4

许多常用词也是有效的正则表达式。你想解决什么问题? – kennytm

+0

只要你不假定这些字符串'​​/ user8099525 /'是一个正则表达式,那么是的,在某种程度上。 – revo

+0

没有字符串是javasript中的“正则表达式”,除非它使用RegExp构造函数进行分析。许多字符串可以制成正则表达式。常见的词可以做成正则表达式,所以如果你问是否有一种方法能够基于某种模式区分两者(视觉上) - 不。如果你问是否可以确定某个变量是字符串还是正则表达式 - 当然这是类型检查,并且与底层字符模式无关。 – Damon

回答

0

假设你想要的目标源(例如:文章),并要检查哪些词最常用的是源:

假设中的文章文本的整个块是在一个字符串,分配到变量“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 
]; 

现在你可以通过console.log(arrWords)来查看结果!