2017-02-18 27 views
1

我甚至不知道如何正確設置標題爲這個問題。所以我一直在嘗試做點什麼,但是我失敗了。我認爲最好在下面展示我想要完成的一些示例。正則表達式將匹配主題相似或相同的字符串

// Let's say I have a list of some tags/slugs. 

$subjects = [ 
    'this-is-one', 
    'might-be-two', 
    'yessir', 
    'indeednodash', 
    'but-it-might' 
]; 

$patterns = [ 
    'this-is-one', // should match $subjects[0] 
    'mightbetwoorthree', // should match $subject[1] 
    'yes-sir', // should match $subject[2] 
    'indeednodash', // should match $subject[3] 
    'but-it-might-be-long-as-well' // should match $subject[4] 
]; 

所以,正如人們可能會看到的......一些模式,不完全/完全匹配給定的主題......所以這是我的問題。我想製作一個正則表達式,它可以匹配所有可能的變體。

我試圖foreach循環中一些基本的東西,但OFC它不會工作,因爲它是不完全匹配......

if (preg_match("/\b$pattern\b/", $subject)) { // ... } 

任何建議,說明和代碼示例,請...我想把我的思想包裝在正則表達式中,但不太好。

我也會給JS添加標籤,因爲沒有必要對phppreg_match做任何事情。

+0

應該necessarly是一個正則表達式???這可能很簡單,使用其他的東西! –

+3

您的主題變體不會太不同,所以我只是在比較之前從主題中刪除任何非字母字符,然後執行簡單的子字符串匹配。對於任何更復雜的東西,除了使用機器學習之外,我不知道如何去做。 –

+0

@ibrahimmahrir - 不一定,但我的假設是,它可能需要這樣的事情? – dvLden

回答

1

function getMatchesOf(pattern, subjects) { 
 
    var result = []; 
 
    pattern = pattern.replace(/[^a-z]/g, ''); 
 
    subjects.forEach(function(subject) { 
 
    var _subject = subject.replace(/[^a-z]/g, ''); 
 
    if(pattern.includes(_subject)) 
 
     result.push(subject); 
 
    }); 
 
    
 
    return result; 
 
} 
 

 

 
var subjects = [ 
 
    'this-is-one', 
 
    'might-be-two', 
 
    'yessir', 
 
    'indeednodash', 
 
    'but-it-might' 
 
]; 
 

 
var patterns = [ 
 
    'this-is-one', 
 
    'mightbe', 
 
    'yes-sir', 
 
    'indeednodash', 
 
    'but-it-might-be-long-as-well' 
 
]; 
 

 
console.log(patterns[0] + " matches: ", getMatchesOf(patterns[0], subjects)); 
 

 
console.log(patterns[4] + " matches: ", getMatchesOf(patterns[4], subjects));

相關問題