【问题标题】:Regex to get values from a string using C#正则表达式使用 C# 从字符串中获取值
【发布时间】:2016-08-13 13:49:30
【问题描述】:

我之前已经发布了这个,但没有给出我想要达到的目标的明确信息。

我正在尝试在 c# 中使用正则表达式从字符串中获取值。我无法理解为什么有些值我可以得到而有些我不能使用类似的方法。

请在下面找到代码 sn-p。 请让我知道我错过了什么。 提前致谢。

string text = "0*MAO-001*20160409*20160408*Encounter Data Duplicates Report       *     *ENC000200800400120160407*PRO*PROD*";

//toget the value 20160409 from the above text
//this code works fine
Regex pattern = new Regex(@"([0][*]MAO[-][0][0][1].*?[*](?<Value>\d+)[*])");
Match match = pattern.Match(text);
string Value = match.Groups["Value"].Value.ToString();



//to get the value ENC000200800400120160407 from the above text
// this does not work and gives me nothing
Regex pattern2 = new Regex(@"([0][*]MAO[-][0][0][1].*?[*].*?[*].*?[*].*?[*].*?[*](?<Value2>\d+)[*])");
Match match2 = pattern.Match(text);
string Value2 = match.Groups["Value2"].Value.ToString();

【问题讨论】:

  • 尝试第二个正则表达式:- ([0][*]MAO[-][0][0][1].*?[*].*?[*].*?[*].*?[*].*?[*](?&lt;Value2&gt;\w+)[*])
  • 哇.. 谢谢.. 它有效.. 你想把它作为答案发布.. 什么是“w+”?
  • 您应该在* 上拆分,而不是使用可能遗漏某些内容的特定字段验证。

标签: c# .net regex string match


【解决方案1】:

您的文件看起来是用“*”分隔的。

您可以使用一个正则表达式来捕获所有值

尝试使用

((?<values>[^\*]+)\*)

作为你的模式。

所有这些值都将被捕获在 values 数组中。

----更新添加c#代码-----

string text = "0*MAO-001*20160409*20160408*Encounter Data Duplicates Report       *     *ENC000200800400120160407*PRO*PROD*";
Regex pattern = new Regex(@"(?<values>[^\*]+)\*");
var matches = pattern.Matches(text);
string Value = matches[3].Groups["values"].Captures[0];
string Value2 = matches[6].Groups["values"].Captures[0];

【讨论】:

  • 我认为你第一次就做对了。但是,要使用捕获集合,它应该被量化(?:(?&lt;values&gt;[^\*]*)\*)+
【解决方案2】:

您需要将其用于第二个正则表达式

([0][*]MAO[-][0][0][1].*?[*].*?[*].*?[*].*?[*].*?[*](?<Value2>\w+)[*])

\w 是集合[A-Za-z0-9_] 中的任何字符。您只使用了 \d 来搜索数字 [0-9],但事实并非如此

C# Code

【讨论】:

    【解决方案3】:

    在您第二次尝试使用正则表达式时,您匹配的是 pattern 而不是 pattern2

    Match match2 = pattern.Match(text);
    string Value2 = match.Groups["Value2"].Value.ToString();
    

    您还使用来自matchGroups 而不是match2

    这就是为什么将变量命名为对它们所代表的有意义的名称很重要。是的,它可能是一个“模式”,但该模式代表什么。当您使用名称模糊的变量时,会产生类似的问题。

    【讨论】:

    • 你是对的..这是一个错误..感谢您的纠正..但是 pattern2 也没有让我得到结果
    【解决方案4】:

    您几乎明白了,但您要查找的字段包含字母和数字。

    这是您第二个固定的正则表达式。

    ([0][*]MAO[-][0][0][1].*?[*](?:.*?[*]){4}(?&lt;Value2&gt;.*?)[*])

     (                             # (1 start)
          [0] [*] MAO [-] [0] [0] [1] .*? [*] 
    
          (?: .*? [*] ){4}
    
          (?<Value2> .*? )              # (2)
          [*] 
     )                             # (1 end)
    

    为了让它不那么忙,这可能会更好

    (0\*MAO-001.*?\*(?:[^*]*\*){4}(?&lt;Value2&gt;[^*]*)\*)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多