【问题标题】:C# RegEx to find values within a stringC# RegEx 在字符串中查找值
【发布时间】:2017-09-03 23:51:48
【问题描述】:

我是 RegEx 的新手。我有一个如下字符串。我想获取 [{# #}]

之间的值

例如:"Employee name is [{#John#}], works for [{#ABC Bank#}], [{#Houston#}]"

我想从上面的字符串中获取以下值。

"John",
"ABC Bank",
"Houston"

【问题讨论】:

  • 你应该看看How to Ask
  • 什么是“#”?数字?有什么事吗?
  • 这不是最好的写作,但对我来说很清楚他想在字符串的哈希之间提取值,看起来像:'[{# EXTRACT_THIS #}]' 正则表达式可能是一种方式这样做
  • @anomeric No # 不是数字。
  • 我们必须知道#是什么。如果我们不知道字符串的其余部分是什么,您就不能指望任何人编写表达式来从字符串中提取数据

标签: c# regex


【解决方案1】:

基于解决方案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】:

    根据解决方案和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.
      }
    }
    

    【讨论】:

      【解决方案3】:
      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;
      
              }
      
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多