簡體   English   中英

正則表達式使用 C# 從字符串中獲取值

[英]Regex to get values from a string using C#

我早些時候發布了這個,但沒有提供關於我想要實現的目標的明確信息。

我正在嘗試使用 c# 中的 Regex 從字符串中獲取值。 我無法理解為什么我可以獲得某些值而某些值我不能使用類似的方法。

請在下面找到代碼片段。 請讓我知道我缺少什么。 提前致謝。

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();

看起來您的文件是 '*' 分隔的。

您可以使用一個正則表達式來捕獲所有值

嘗試使用

((?<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];

在您第二次嘗試使用正則表達式時,您匹配的是pattern而不是pattern2

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

您還使用來自match而不是match2Groups

這就是為什么將變量命名為對它們所代表的含義有意義的原因很重要。 是的,它可能是一種“模式”,但該模式代表什么。 當您使用名稱含糊的變量時,會產生類似這樣的問題。

您需要將此用於第二個正則表達式

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

\\w是集合[A-Za-z0-9_]任何字符。 您只使用\\d搜索數字[0-9]而不是這種情況

C# 代碼

您幾乎知道了,但是您要查找的字段包含字母和數字。

這是您修復的第二個正則表達式。

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

 (                             # (1 start)
      [0] [*] MAO [-] [0] [0] [1] .*? [*] 

      (?: .*? [*] ){4}

      (?<Value2> .*? )              # (2)
      [*] 
 )                             # (1 end)

為了讓它不那么忙,這可能會更好

(0\\*MAO-001.*?\\*(?:[^*]*\\*){4}(?<Value2>[^*]*)\\*)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM