2016-08-02 73 views
1

我有模式字符串:「{Name}您好,歡迎{國家}
和一個完整的字符串值:’您好斯科特,歡迎越南
哪有我提取{Name}和{Country}的值:
Name = Scott,Country = VietNam
我已經看到一些正則表達式來解決這個問題,但我可以在這裏應用模糊匹配嗎?
例如用翻譯字符串「歡迎來到越南,你好斯科特」,我們還必須改變正則表達式嗎?獲取字符串值

+0

我投票結束這個問題作爲題外話,因爲它不包含最小代碼來重現問題。 –

+0

我嘗試過使用正則表達式,但實際的問題是如何以較少的改變表達式來提取值。 – phuongnd

+0

@phuongnd更新後的答案,它將雙向工作。 – 2016-08-02 03:17:20

回答

1

作爲一個更通用的解決方案,你可以這樣做以下:

public Dictionary<string, string> GetMatches(string pattern, string source) 
{ 
    var tokens = new List<string>(); 
    var matches = new Dictionary<string, string>(); 

    pattern = Regex.Escape(pattern); 

    pattern = Regex.Replace(pattern, @"\\{.*?}", (match) => 
     { 
      var name = match.Value.Substring(2, match.Value.Length - 3); 

      tokens.add(name); 

      return $"(?<{name}>.*)"; 
     }); 

    var sourceMatches = Regex.Matches(source, pattern); 

    foreach (var name in tokens) 
    { 
     matches[name] = sourceMatches[0].Groups[name].Value; 
    } 

    return matches; 
} 

該方法從圖案中提取標記名稱,然後替換具有與名爲capture組的正則表達式具有相同語法的標記。接下來,它使用修改的模式作爲正則表達式來提取源字符串中的值。最後,它使用捕獲的令牌名稱與指定的捕獲組來構建要返回的字典。

+0

有史以來最好的解決方案! – phuongnd

3

您可以使用正則表達式:

var Matches = Regex.Matches(input, @"hello\s+?([^\s]*)\s*|welcome\s+?to\s+?([^\s]*)", RegexOptions.IgnoreCase); 

string Name = Matches.Groups[1].Value; 
string Country = Matches.Groups[2].Value; 

更新:更改代碼工作無論哪種方式。 Demo

+1

更好的是,使用正則表達式從模板中提取標記並構建新的正則表達式,其中原始標記被替換爲已命名的捕獲組,並且字符串的其餘部分將被轉義。 – seairth

0

只是快速和骯髒的..

string pattern = "Hello Scott, welcome to VietNam"; 

var splitsArray = pattern.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries); 
var Name = splitsArray[1].Replace(",", string.Empty); 
var country = splitsArray[4];