【发布时间】:2020-11-25 19:03:59
【问题描述】:
我正在尝试找出一种使用正则表达式将字符串提取为两个值的方法。一个示例字符串是 “区域商店 1 - 麦迪逊 [RSM1]” "区域商店 2 [SS2]"
我想让它们提取到“Regional Store 1 - Madison”、“RSM1”和“Regional Store 2”、“SS2”。
我尝试使用正则表达式 (?
由于字符串将始终遵循“{Name} [{code}]”的格式,我想知道我是否应该只使用 string.split。
【问题讨论】:
-
"Regional Store 1 - Madison [RSM1]" "Regional Store 2 [SS2]"是一个完整的字符串还是你的意思是将它写成两个单独的字符串?双引号是字符串的一部分吗? -
如果 {Name} 部分不能包含“[”或“]”,我认为
string[] parts = myFullString.Split(new char[] { '[',']'},StringSplitOptions.RemoveEmptyEntries)应该在不使用 TrimEnd 的情况下解决问题。如果它也可以包含这些字符,我会选择int indx = myFullString.LastIndexOf('['); string Name = myFullString.Substring(0, indx); string Code = myFullString.Substring(indx + 1, myFullString.Length - indx - 2); -
如果每次只有一行指定格式那么你可以这样使用:var matches = Regex.Matches("Regional Store 1 - Madison [RSM1]", "([^\[ \]]+)\w").ToArray(); var 结果 = $"{matches[0].Value}={matches[1].Value}";
标签: c# .net regex string .net-core