如何拆分以“[* word *]”为其组成部分的字符串

时间:2015-11-30 14:27:14

标签: c# string

实施例: 对于像这样的字符串:“ www.google.com [Google] ”拆分部分将是: 1.“ www.google.com ” 2.“ Google

www.google.com [Google] ”的相同拆分结果(在这种情况下,两个部分之间没有空格)

2 个答案:

答案 0 :(得分:3)

也许是String.Split

string[] parts = input.Split('[').Select(s => s.Trim('[',']', ' ')).ToArray();

如果这样的字符串是可能的,并且也应该只产生两个部分:

www.google.com    [[[Google]]]

您可以使用StringSplitOptions.RemoveEmptyEntries

string[] parts = input.Split(new []{'['}, StringSplitOptions.RemoveEmptyEntries)
    .Select(s => s.Trim(']', ' ')).ToArray();

答案 1 :(得分:1)

您可以使用正则表达式:

([\w.\/]*)\s*\[(\w*)\]

您将有两个组,然后可以从匹配中提取:

1.  [0-14]  `www.google.com`
2.  [16-22] `Google`

在线演示:https://regex101.com/r/vX8hS7

示例:https://dotnetfiddle.net/IPDuPo

string input = "www.google.com[Google]";
Match match = Regex.Match(input, @"([\w.\/]*)\s*\[(\w*)\]");

foreach(Group group in match.Groups)
{
    Console.WriteLine(group.Value);
}

将输出:

www.google.com[Google]
www.google.com
Google

请注意,在线正则表达式演示中,整个匹配不包含在组中,但在.NET中,整个匹配作为第一组包含在输出中。