splitArguments property

Iterable<string> get splitArguments

Splits a string by whitespace, but only those whitespaces that are outside of quotes.

This function handles both single and double quotes. It splits the input string at spaces that are not enclosed within quotes.

  • Parameter input: The input string to be split.
  • Returns: A list of substrings split by whitespace outside of quotes.

Implementation

Iterable<string> get splitArguments {
  if (isBlank) {
    return [];
  }
  List<String> result = [];
  StringBuffer current = StringBuffer();
  bool inSingleQuotes = false;
  bool inDoubleQuotes = false;

  for (int i = 0; i < this!.length; i++) {
    String char = this![i];

    if (char == '"' && !inSingleQuotes) {
      inDoubleQuotes = !inDoubleQuotes;
      current.write(char);
    } else if (char == "'" && !inDoubleQuotes) {
      inSingleQuotes = !inSingleQuotes;
      current.write(char);
    } else if (char == ' ' && !inSingleQuotes && !inDoubleQuotes) {
      if (current.isNotEmpty) {
        result.add(current.toString());
        current.clear();
      }
    } else {
      current.write(char);
    }
  }

  if (current.isNotEmpty) {
    result.add(current.toString());
  }

  return result;
}