Split string by (') and Spaces but keep any space character between two consecutive (')

Viewed 114

I need to split a string by (' ') or (''') but if in the string appears ' ' I want to keep only that space. this are examples of the string:

  1 7871.6 LIQ WCT GOR THP ' ' FIELD BHP /
  1 7871.6 'LIQ' 'WCT' 'GOR' 'THP' ' ' FIELD BHP /

and I want the output to be:

1
7871.6
LIQ
WCT
GOR
THP

FIELD
BHP
/

Any help would be appreciated

2 Answers

Something like this should get he job done.. that is if you don't mind your head exploding from a regex.. p.s this should cover your weird extra case :) Oh and just so I make sure I credit the right people I got the regex for this from https://stackoverflow.com/a/51432792/5963888

var str = "1 7871.6 'LIQ' 'WCT' 'GOR' \"THP\" ' ' 'LIQ WCT GOR' FIELD BHP /";
var regex = new System.Text.RegularExpressions.Regex("([\"'])((?:\\\\1|(?:(?!\\1)).)*)(\\1)");
var match = regex.Matches(str)
    .Select(e => e.Groups)
    .Select( e => e[2].Value)
    .SelectMany( e =>
    {
        if(!(e.Trim() == String.Empty))
        {
            return e.Split();
        }
        return new[] { e };
    });
System.Console.WriteLine(String.Join(Environment.NewLine, match));

Here is some code that does the trick

    string str = "1 7871.6 'LIQ' 'WCT' 'GOR' 'THP' ' ' FIELD BHP /";


    string replaceToken  = "someValueThatYouChose";
    str = str.Replace(" ' ' ", $" {replaceToken} ");
    str = str.Replace("'", "");
    string[] splitValues = str.Split(" ");
    for (int i = 0; i < splitValues.Length; i++)
    {
        if(splitValues[i] == replaceToken){
            splitValues[i] = " ";
        }
    }
    // Here is your output
    foreach (var value in splitValues)
    {
        Console.WriteLine(value);
    }
Related