简体   繁体   English

C# 正则表达式 - 提取字符串的多个部分

[英]C# Regex - Extract multiple parts of string

In C#, I am trying to extract multiple parts (in bold & italic) of string which would be in below format.在 C# 中,我试图提取以下格式的字符串的多个部分(粗体和斜体)。 Note thats numbers could be 6-7 digits longer so don't need any restriction on length however first part of string in bold italic would always be 3 char long.请注意,数字可能长 6-7 位,因此不需要对长度进行任何限制,但是粗斜体字符串的第一部分始终为 3 个字符长。

TCS- TST .MSL-M365-SPO.S 8629 -O 2887 .Engagement TCS- TST .MSL-M365-SPO.S 8629 -O 2887 .Engagement

At the moment I am using string.Split() which requires splitting string multiple times and extracting the part I need.目前我正在使用 string.Split() ,它需要多次拆分字符串并提取我需要的部分。 So was wondering if there's better way to do it using REGEX.所以想知道是否有更好的方法来使用 REGEX。

Try some online tools .尝试一些在线工具

^\w{3}-(?<First>\w{3}).\w{3}-\w\d+-\w{3}.\w(?<Second>\d+)-\w(?<Third>\d+).\w+$

This is a good start, then use group names to extract values:这是一个好的开始,然后使用组名来提取值:

var regex = new Regex(@"^\w{3}-(?<First>\w{3}).\w{3}-\w\d+-\w{3}.\w(?<Second>\d+)-\w(?<Third>\d+).\w+$");
var match = regex.Match(input);
if (!match.Success)
    return;

var first = match.Groups["First"];
var second = match.Groups["Second"];
var third = match.Groups["Third"];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM