flux
flux

Reputation: 1648

RegEx split string into words by space and containing chars

How can one perform this split with the Regex.Split(input, pattern) method?

This is a [normal string ] made up of # different types # of characters

Array of strings output:

1. This 
2. is
3. a
4. [normal string ]
5. made
6. up
7. of
8. # different types #
9. of
10. characters

Also it should keep the leading spaces, so I want to preserve everything. A string contains 20 chars, array of strings should total 20 chars across all elements.

What I have tried:

Regex.Split(text, @"(?<=[ ]|# #)")

Regex.Split(text, @"(?<=[ ])(?<=# #")

Upvotes: 2

Views: 2716

Answers (3)

Nahuel Fouilleul
Nahuel Fouilleul

Reputation: 19315

It would be easier using matching approach however it can be done using negative lookeaheads :

[ ](?![^\]\[]*\])(?![^#]*\#([^#]*\#{2})*[^#]*$)

matches a space not followed by

  • any character sequence except [ or ] followed by ]
  • # followed by an even number of #

Upvotes: 1

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186698

I suggest matching, i.e. extracting words, not splitting:

string source = @"This is a [normal string ] made up of # different types # of characters";

// Three possibilities:
//   - plain word [A-Za-z]+
//   - # ... # quotation
//   - [ ... ] quotation  
string pattern = @"[A-Za-z]+|(#.*?#)|(\[.*?\])";

var words = Regex
  .Matches(source, pattern)
  .OfType<Match>()
  .Select(match => match.Value)
  .ToArray();

Console.WriteLine(string.Join(Environment.NewLine, words
  .Select((w, i) => $"{i + 1}. {w}")));

Outcome:

1. This
2. is
3. a
4. [normal string ]
5. made
6. up
7. of
8. # different types #
9. of
10. characters

Upvotes: 2

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626861

You may use

var res = Regex.Split(s, @"(\[[^][]*]|#[^#]*#)|\s+")
    .Where(x => !string.IsNullOrEmpty(x));

See the regex demo

The (\[[^][]*]|#[^#]*#) part is a capturing group whose value is output to the resulting list along with the split items.

Pattern details

  • (\[[^][]*]|#[^#]*#) - Group 1: either of the two patterns:
    • \[[^][]*] - [, followed with 0+ chars other than [ and ] and then ]
    • #[^#]*# - a #, then 0+ chars other than # and then #
  • | - or
  • \s+ - 1+ whitespaces

C# demo:

var s = "This is a [normal string ] made up of # different types # of characters";
var results = Regex.Split(s, @"(\[[^][]*]|#[^#]*#)|\s+")
    .Where(x => !string.IsNullOrEmpty(x));
Console.WriteLine(string.Join("\n", results));

Result:

This
is
a
[normal string ]
made
up
of
# different types #
of
characters

Upvotes: 1

Related Questions