2017-06-01 104 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)來查看結果!