Extract values ​​from comma-separated lists

When setting a list of values ​​separated by commas, such as 3, asdf, *#, 1212.3, I would like to extract each of these values, not counting the comma, so I will have a list of values, for example [3, "asdf", "*#", 1212.3](and not as a textual representation like this, but as an array of "hits"). How should I do it?

+3
source share
4 answers

First, if you are dealing with CSV files, do not use a regular expression or your own parser. Basically, when you think that everything is simple, they really are not, Stop Rolling Your Own CSV Parser .

Next, you say you want to have an array ([3, "asdf", "* #", 1212.3]). This is similar to type mixing and cannot be done in a static language. And ultimately very inefficient even using std.variant. For each value analyzed, you should have a code:

try {
    auto data = to!double(parsedValue);
    auto data2 = to!int(data);
    if(data == data2)
        returnThis = Variant(data2);
    else
        returnThis = Variant(data);
} catch(ConvException ce) { }

Now, if your data is really separated by a specific character set and not broken into newline entries, you can use split (",") from std.algorithm. Otherwise, use the CSV parser. If you do not want to follow the standard parser wrappers, the data is yours. In your example, you have spaces that should not be ignored in CSV format, so call strip () on the output.

, , , , . , CSV, , . , , CSV.

, , CSV Parser D. , , , . unittest. :

struct MyData {
    int a;
    string b;
    string c;
    double d
}

foreach(data; csv.csv!MyData(str)) // I think I'll need to change the module/function name
    //...
+2

, D. CSV D.

+5

in perl you can do something like:

@anArray = split(',', "A,B,C,D,E,F,G");
+1
source

(?:,|\s+)?([^ ,]+)must do. It skips a comma or space, then selects anything but a comma or space. Change the taste.

0
source

Source: https://habr.com/ru/post/1780594/


All Articles