【问题标题】:Regular Expression split string and get whats in brackets [ ] put into array正则表达式拆分字符串并将括号 [] 中的内容放入数组
【发布时间】:2013-10-22 04:10:00
【问题描述】:

我正在尝试使用正则表达式将字符串拆分为 2 个数组,结果是这样的。

String str1 = "First Second [insideFirst] Third Forth [insideSecond] Fifth";

如何将 str1 拆分为 2 个如下所示的数组:

ary1 = ['First Second','Third Forth','Fifth'];
ary2 = ['insideFirst','insideSecond'];

【问题讨论】:

标签: c# asp.net regex split


【解决方案1】:

这是我的解决方案

string str = "First Second [insideFirst] Third Forth [insideSecond] Fifth";
MatchCollection matches = Regex.Matches(str,@"\[.*?\]");
string[] arr = matches.Cast<Match>()
                      .Select(m => m.Groups[0].Value.Trim(new char[]{'[',']'}))
                      .ToArray();
foreach (string s in arr)
{
    Console.WriteLine(s);
}

string[] arr1 = Regex.Split(str,@"\[.*?\]")
                     .Select(x => x.Trim())
                     .ToArray();
foreach (string s in arr1)
{
    Console.WriteLine(s);
}

输出

insideFirst
insideSecond
First Second
Third Forth
Fifth

【讨论】:

  • 这很接近,只有当你实际上只用方括号分割时。但在我看来,OP 显然使用了一个示例来解决这个问题,而不是他希望拆分的文字字符串。代替方括号的示例,他很可能会被其他更复杂的模式分割。
  • 这个问题字面意思是方括号。如果 OP 想要别的东西,他可以在他的问题中这么说。 OP也接受了这个作为正确答案。我认为最好不要做出自己的假设。
  • 实际上,它在 OP 问题中的任何地方都没有说“方括号”。你的回答很棒,而且很有用。但是我们(应该)都明白方括号是 Some-Variable-Parameter 的通用符号。例如:Suamere [中间名] 标量。我的中间名不是[MiddleName],他当然没有被[insideFirst] 分开。即使他想说方括号内的文字,他也没有,我认为他没有。据我们所知,他接受了您的答案c# code,并更改了其中的正则表达式模式。他不说。所以我的观点是:这个问题应该按要求回答。
  • 在问题中他说“括号 []”。他在“括号”这个词后面加上了两个第三个括号符号,我认为它描绘了 OP 打算分裂这两个字符的意图。因此我说这个问题的字面意思是方括号。
【解决方案2】:

请尝试以下代码。它对我来说工作正常。

  String str1 = "First Second [insideFirst] Third Forth [insideSecond] Fifth";
    var output = String.Join(";", Regex.Matches(str1, @"\[(.+?)\]")
                                .Cast<Match>()
                                .Select(m => m.Groups[1].Value));

    string[] strInsideBreacket = output.Split(';');


    for (int i = 0; i < strInsideBreacket.Count(); i++)
    {
        str1 = str1.Replace("[", ";");
        str1 = str1.Replace("]", "");
        str1 = str1.Replace(strInsideBreacket[i], "");
    }

    string[] strRemaining = str1.Split(';');

调试代码时请看下面的输出屏幕截图:

这里, strInsideBreacket 是像 insideFirst 和insideSecond 这样的括号值数组 而strRemaining 是First Second、Third Forth 和Fifth 的数组

谢谢

【讨论】:

  • 这不好,因为实现知道模式。例如:如果您要使用名为 SplitByPattern 的解决方案创建一个函数,该函数返回拆分结果的集合以及生成的正则表达式分隔符的集合,那么您的函数只有在模式完全是方括号时才能工作。但是,很明显,OP 使用的测试数据表明他不会按字面意思被方括号分割。所以你的功能会失败。
【解决方案3】:

试试这个解决方案,

 String str1 = "First Second [insideFirst] Third Forth [insideSecond] Fifth";
 var allWords = str1.Split(new char[] { '[', ']' }, StringSplitOptions.RemoveEmptyEntries);
 var result = allWords.GroupBy(x => x.Contains("inside")).ToArray();

想法是,首先获取所有单词,然后将其分组。

【讨论】:

  • 一般来说,找到一个非正则表达式解决方案总是很棒的。但是OP在问一个通用的问题。他仅使用方括号作为普遍理解的文本来表示可选文本或示例文本。如果他希望分割的模式没有明显的具体字符,例如:\d+\w{2,3},那么这不起作用。你来自一个好地方,但这无助于回答这个特定的问题。
【解决方案4】:

在我看来,“user2828970”提出了一个带有示例的问题,而不是他想要解析的文字文本。在我看来,他很可能会问这个问题:

我正在尝试使用正则表达式来拆分这样的字符串。

var exampleSentence = "I had 185 birds but 20 of them flew away";
var regexSplit = Regex.Split(exampleSentence, @"\d+");

regexSplit 的结果是:I hadbirds butof them flew away

但是,我也想知道导致 second 字符串与其前面的文本分离的值,以及导致 third 字符串分离的值来自 its 前面的文本。即:我想知道18520

字符串可以是任何东西,分割的模式可以是任何东西。答案不应包含硬编码值。

嗯,这个简单的函数将执行该任务。可以优化代码以编译正则表达式,或重新组织以返回多个集合或不同的对象。但这(几乎)是我在生产代码中使用它的方式。

public static List<Tuple<string, string>> RegexSplitDetail(this string text, string pattern)
{
    var splitAreas = new List<Tuple<string, string>>();

    var regexResult = Regex.Matches(text, pattern);
    var regexSplit = Regex.Split(text, pattern);

    for (var i = 0; i < regexSplit.Length; i++)
        splitAreas.Add(new Tuple<string, string>(i == 0 ? null : regexResult[i - 1].Value, regexSplit[i]));

    return splitAreas;
}

...
var result = exampleSentence.RegexSplitDetail(@"\d+");

这将返回一个如下所示的集合:

{ null, "I had "}, // First value, had no value splitting it from a predecessor
{"185", " birds but "}, // Second value, split from the preceding string by "185"
{ "20", " of them flew away"} // Third value, split from the preceding string by "20"

【讨论】:

    【解决方案5】:

    由于这是一个 .NET 问题,并且除了我在其他答案中更喜欢的方法之外,您还可以通过另一种非常简单的方法来捕获拆分值。然后,您只需要创建一个函数来利用您认为合适的结果。

    var exampleSentence = "I had 185 birds but 20 of them flew away";
    var regexSplit = Regex.Split(exampleSentence, @"(\d+)");
    

    regexSplit 的结果是:I had185birds but20of them flew away。如您所见,拆分结果中存在拆分值。

    请注意与我的其他答案相比的细微差别。在这个正则表达式拆分中,我在整个模式(\d+) 周围使用了一个捕获组你不能这样做!!!?...你可以吗?

    在拆分中使用捕获组将强制拆分结果捕获组之间的拆分值的所有捕获组。这可能会变得混乱,所以我不建议这样做。它还迫使使用您的函数的人知道他们必须将正则表达式包装在捕获组中。

    【讨论】:

      猜你喜欢
      • 2018-09-06
      • 1970-01-01
      • 2012-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 2016-12-03
      相关资源
      最近更新 更多