[英]Get a substring from a substring of a string in C# using regex
我想提取一個 substring 遵循特定的 substring 並以長字符串中的特定字符結尾。
我有一個長字符串: "<can be whatever characters or string>CSVSegment.ab12\<can be whatever characters or string>CSVSegment.cd34\<can be whatever>"
我只想提取ab12和cd34 ,基本上是在CSVSegment之后並在 \ 之前結束的任何內容
目前我正在做
Regex pattern = new Regex(@"CSVSegment.(?<SegmentName>))\");
Match match = pattern.Match(longstring);
我不知道如何為此使用組,以及如何獲取遵循 CSVSegment 的字符串列表。 並在 \ 之前結束長字符串中的所有出現。
據我所知,你想匹配
ab12
cd34
從
....CSVSegment.ab12\....
....CSVSegment.cd34\....
你可以用CSVSegment\.(?<SegmentName>[^\\]*)\\
模式來做到這一點:
Regex pattern = new Regex(@"CSVSegment\.(?<SegmentName>[^\\]*)\\");
var result = pattern
.Match(source)
.Groups["SegmentName"]
.Value;
或者,如果您想要所有匹配項
var results = pattern
.Matches(source)
.Cast<Match>()
.Select(m => m.Groups["SegmentName"].Value)
.ToArray();
模式CSVSegment\.(?<SegmentName>[^\\]*)\\
解釋:
CSVSegment\. - prefix, note that dot ('.') has been escaped
(?<SegmentName>[^\\]*) - zero or more any symbols but \
\\ - suffix \, note escapement
在這里我們需要擒縱機構,因為.
(點)表示任何字符, \
表示轉義符號。
你需要類似的東西:
Regex pattern = new Regex(@"CSVSegment\.(?<sn>[a-z0-9]{4})\");
MatchCollection matches = pattern.Matches(longstring);
foreach(Match m in mc)
Console.WriteLine(m.Groups["sn"].Value);
您真正偏離軌道的唯一部分是沒有在命名的捕獲組中放置模式。 與組內的模式匹配的任何內容都將在組值中結束。 我放置了一個與ab12和cd34示例匹配的[a-z0-9]{4}
模式,但如果您的數據范圍更廣,您可能希望更改此模式以匹配將看到的值
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.