简体   繁体   English

从字符串 C# 正则表达式中提取标记

[英]Extract tokens from the string C# regex

I got string which needs to be separated by pipe |.我得到需要用 pipe | 分隔的字符串。

The numeric tokens can be defined without wrapping in anything like 20 and 50 in the example below or could be defined in [] or {}.在下面的示例中,数字标记可以在不包含任何内容的情况下定义,例如 20 和 50,或者可以在 [] 或 {} 中定义。

The string token will be either wrapped in [] or {} and can have any special characters including |字符串标记将包裹在 [] 或 {} 中,并且可以包含任何特殊字符,包括 | separator within the token.令牌中的分隔符。 They cannot have [] or {} within the token string.它们不能在令牌字符串中包含 [] 或 {}。

[Name1]|20|[Nam|2]|{Na;me,3}|50|[Na|me!@#$%^&*()Finish]|[25]|{67} [Name1]|20|[Nam|2]|{Na;me,3}|50|[Na|me!@#$%^&*()完成]|[25]|{67}

Need to extract above string to following tokens:需要将上面的字符串提取到以下标记:

Name1姓名1

20 20

Name|2名称|2

Na;me,3我,3

50 50

Na|me!@#$%^&*()Finish Na|me!@#$%^&*()完成

25 25

67 67

How can we do that in C#?我们如何在 C# 中做到这一点? Is regular expressions best way to go about it?正则表达式最好的办法是go一下吗?

You can extract them with你可以用

\[(?<r>[^][]*)]|\{(?<r>[^{}]*)}|(?<r>[^|]+)

See the regex demo .请参阅正则表达式演示 Details :详情

  • \[(?<r>[^][]*)] - [ , then any zero or more chars other than [ and ] captured into Group "r", and then a ] char \[(?<r>[^][]*)] - [ ,然后[]以外的任何零个或多个字符捕获到组“r”,然后是]字符
  • | - or - 或者
  • \{(?<r>[^{}]*)} - { , then any zero or more chars other than { and } captured into Group "r", and then a } char \{(?<r>[^{}]*)} - { ,然后除{}之外的任何零个或多个字符捕获到组“r”中,然后是一个}字符
  • | - or - 或者
  • (?<r>[^|]+) - any one or more chars other than a | (?<r>[^|]+) - 除|以外的任何一个或多个字符char captured in Group "r".在组“r”中捕获的字符。

See the C# demo :请参阅C# 演示

var text = "[Name1]|20|[Nam|2]|{Na;me,3}|50|[Na|me!@#$%^&*()Finish]|[25]|{67}";
var pattern = @"\[(?<r>[^][]*)]|\{(?<r>[^{}]*)}|(?<r>[^|]+)";
var result = Regex.Matches(text, pattern).Cast<Match>().Select(x => x.Groups["r"].Value);
foreach (var s in result)
    Console.WriteLine(s);

Output: Output:

Name1
20
Nam|2
Na;me,3
50
Na|me!@#$%^&*()Finish
25
67

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

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