Break a string into String Array

BigH61 581 Reputation points

Is it possible to break the following string into a string array?

"Test string[Page#][TimeDate]that is difficult to break down."

String Array should be

Test string



that is difficult to break down.

NOTE The string may or may not contain items with in [].

There is a Set list of items within [] that can be added to the string. For the purposes of this question lets say they are [Page#], [TimeDate], [Time]. The user can also use [] but these items are not to be extracted separately. For example

"Test string[Page#][TimeDate]that is difficult to [break] down."

String Array should be;

Test string



that is difficult to [break] down.

Thank you for any assistance.

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,464 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 113.7K Reputation points

    Check an example that uses Regular Expressions:

    string[] items = { "[Page#]", "[TimeDate]", "[Time]" };
    string input = "Test string[Page#][TimeDate]that is difficult to [break] down.";
    string j = string.Join( "|", items.Select( i => Regex.Escape( i ) ) );
    string pattern = $@"(?:(?!{j}).)+|{j}";
    string[] result = Regex.Matches( input, pattern ).Cast<Match>( ).Select( m => m.Value ).ToArray( );

    (In .NET you can omit the .Cast<Match>( )).

0 additional answers

Sort by: Most helpful