2017-09-03 105 views
-3

我是RegEx的新手。我有一个像下面的字符串。我想[{##}]C#RegEx查找字符串中的值

防爆之间的值:"Employee name is [{#John#}], works for [{#ABC Bank#}], [{#Houston#}]"

我想从上面的字符串得到以下值。基于该解决方案

"John", 
"ABC Bank", 
"Houston" 
+1

你应该看看[问] – pvg

+0

什么是“#”?数字?什么? – anomeric

+0

这不是最好的作品不断,但他希望在字符串中提取的散列值之间,看起来像它看起来很清楚对我说:“[{#EXTRACT_THIS#}]”正则表达式可能是这样做 – Tico

回答

0

基于解决方案Regular Expression Groups in C#。 你可以试试这个:

 string sentence = "Employee name is [{#john#}], works for [{#ABC BANK#}], 
     [{#Houston#}]"; 
     string pattern = @"\[\{\#(.*?)\#\}\]"; 

     foreach (Match match in Regex.Matches(sentence, pattern)) 
     { 
      if (match.Success && match.Groups.Count > 0) 
      { 
       var text = match.Groups[1].Value; 
       Console.WriteLine(text); 
      } 
     } 
     Console.ReadLine(); 
-2
using System; 
using System.Text.RegularExpressions; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      Console.WriteLine(Test("the quick brown [{#fox#}] jumps over the lazy dog.")); 
      Console.ReadLine(); 
     } 

     public static string Test(string str) 
     { 

      if (string.IsNullOrEmpty(str)) 
       return string.Empty; 


      var result = System.Text.RegularExpressions.Regex.Replace(str, @".*\[{#", string.Empty, RegexOptions.Singleline); 
      result = System.Text.RegularExpressions.Regex.Replace(result, @"\#}].*", string.Empty, RegexOptions.Singleline); 

      return result; 

     } 

    } 
} 
1

awesome breakdown for matching patterns inside wrapping patterns你可以尝试:

\[\{\#(?<Text>(?:(?!\#\}\]).)*)\#\}\]

\[\{\#[{#\#\}\]你逃脱片头是#}]逃脱关闭顺序。

你的内在价值是一个名为Text匹配的小组。

string strRegex = @"\[\{\#(?<Text>(?:(?!\#\}\]).)*)\#\}\]"; 
Regex myRegex = new Regex(strRegex, RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Singleline); 
string strTargetString = @"Employee name is [{#John#}], works for [{#ABC Bank#}], [{#Houston#}]"; 

foreach (Match myMatch in myRegex.Matches(strTargetString)) 
{ 
    if (myMatch.Success) 
    { 
    var text = myMatch.Groups["Text"].Value; 

    // TODO: Do something with it. 
    } 
}