My Regex.Split with '\n' takes up two spaces instead of 1

Viewed 52

I need to split my text into each word, space, and new line. Although the words and spaces are properly working, the \n is taking up two spaces only if it's not after a word. Example: "\nTest\nword", here, the first \n takes up two spaces while the second one takes up one.

How would I write the proper regex?

My code:

string delimiterChars = "([ \r\n])";
wordArray = Regex.Split(myTexy, delimiterChars);

For context, I am using Unity.

Input: enter image description here

Output: enter image description here

On the output of the picture: The first element is empty and the second is \n here. I don't want the empty element.

4 Answers

Regex.Split will always produce empty items where the matches are consecutive, or when they are at the start/end of string.

Instead, you can use a matching and extracting approach:

string delimiterChars = "[^ \r\n]+|[ \r\n]";
string[] wordArray = Regex.Matches(myTexy, delimiterChars)
        .Cast<Match>()
        .Select(m => m.Value)
        .ToArray();

The [^ \r\n]+|[ \r\n] regex matches one or more chars other than a space, CR and LF, or a space, CR or an LF char.

Try this :-

string myStr = "This is test text";
            wordArray = myStr.Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);

Output:

enter image description here

You can use regular expressions to remove leading delimiter characters.

    var myTexy = "\nTest\nword";
    string delimiterChars = "([ \r\n])";
    myTexy = Regex.Replace(myTexy, "^" + delimiterChars, "");
    var wordArray = Regex.Split(myTexy, delimiterChars);

The "^" regex option says only look for these characters at the beginning of the string.

Also, just so you are aware the behavior you are seeing is intended and is documented here:

If a match is found at the beginning or the end of the input string, an empty string is included at the beginning or the end of the returned array.

Let me know if this is what you are looking for -

String text = "\nTest\nword"; string[] words = Regex.Split(text, @"(\n+)");

Output - enter image description here

Related