2016-03-02 77 views
0

我有一個簡單的問題,我希望有人能夠爲我闡明一些亮點。正則表達式從列表中找到完全匹配

RegEx還是新的,所以這種行爲對我來說沒有意義。我正在使用C#編寫一個簡單的函數,用於搜索給定字符串中的子字符串列表以及字符串中的子字符串位置。我的代碼如下所示:

DataTable matchtable = new DataTable(); 
string searchstring = " Take a left in 2.1 miles. Then take a right in 3 miles"; 
var substringlist = new [] {"2.1 miles", "3 miles", "4.1 miles", "1","take"}; 
string searchregexstr = string.(@"(\W|^){0}(\W|$)", string.Join("|", substringlist)); 
Regex searchregex = new Regex(searchregexstr); 
if (searchregex.IsMatch(searchstring)) 
{ 
    foreach (Match substring in searchregex.Matches(searchstring)) 
    { 
     string substringmatch = substring.toString(); 
     int indexofsubstringmatch = searchstring.IndexOf(substringmatch); 
     matchtable.Rows.Add(susbtringmatch, indexofsubstringmatch); 
    } 
    return matchtable; 
} 
return matchtable; 

隨着我的主要的正則表達式匹配功能看起來像這樣:

string searchregexstr = string.(@"(\W|^){0}(\W|$)", string.Join("|", substringlist)); 

我的問題是:

當我的匹配表結果看,我得到一擊這兩個2.1英里和1(這是2.1內匹配)

我假設(我認爲不正確),我的正則表達式只查找完整的匹配,其中1不應該匹配,因爲我t在字符串中找不到。

是否有什麼突出的缺失?

非常感謝您提前提供任何幫助!

Zinga

回答

0

那麼,你可以在很多方面做到這一點。例如以下代碼將返回您在特定字符串中找到的術語索引列表。

public static IEnumerable<int> GetStringIndices(IEnumerable<string> substringlist, string data) 
{ 
    var lstIndices = new List<int>(); 

    foreach (var searchString in substringlist) 
    { 
     var regexObj = new Regex([email protected]"(?<=(\s|^)){searchString}(?=(\s|$)|(\W)+?)", 
      RegexOptions.IgnoreCase | RegexOptions.Multiline); 

     var matchResults = regexObj.Match(data); 

     if (!matchResults.Success) 
     { 
      lstIndices.Add(-1); 
      continue; 
     } 

     while (matchResults.Success) 
     { 
      var idx = matchResults.Index; 
      lstIndices.Add(idx); 

      matchResults = matchResults.NextMatch(); 
     } 
    } 
    return lstIndices; 
} 

如果我通過搜索字符串和術語你上面

var data = "Take a left in 2.1 miles. Then take a right in 3 miles"; 
var substringlist = new[] { "2.1 miles", "3 miles", "4.1 miles", "1", "take" }; 
var indices = GetStringIndices(substringlist, data); 

,你會得到一個名爲指標變量指標的列表中提及。最終結果將是

[15,48,-1,17 0,32]

2.1英里在索引15

3.1被發現是在索引48等。

0

你的代碼中有一些錯誤,例如,string.(toStringsusbtringmatch,並沒有列添加行到DataTable時運行時錯誤。順便說一句,你真的需要一個DataTable

string searchregexstr = string.Format(@"(\W|^){0}(\W|$)", string.Join("|", substringlist)); 

這些比賽:

2.1 miles (with leading space) 
take (with trailing space) 
3 miles 

最後,你不

已經糾正了錯別字,並刪除DataTable,如果你糾正這一行這樣的代碼工作正常,我t需要第一個return,因爲最後一個就足夠了。

如果您需要幫助調整正則表達式,我強烈建議RegExr