Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 33 additions & 4 deletions SplitQuotedString/QuotedStringSplitter.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Text;
using System.Collections.Immutable;
using System.Text;

namespace HunnyR.Tools;

Expand All @@ -25,6 +26,8 @@ public class QuotedStringSplitter
/// </summary>
public bool TreatTwoQuotesAsLiteral { get; set; } = false;

private const string CommonCharactersErrorMessage = "The delimiters and quoters have common characters. This might lead to undesired result. Quoters will always be evaluated first!";

/// <summary>
/// quote characters
/// default are double quote(") and single quote (')
Expand All @@ -33,16 +36,42 @@ public class QuotedStringSplitter
/// '"a.b"' will return ["a.b"] not matter what delimiters
/// ''a.b'' will return ["a","b"] if . is the delimiter and TreatTwoQuotesAsLiteral as literal is false else it will return ["'a.b'"]
/// </summary>
public HashSet<char> Quoters { get; set; } = ['"', '\''];
private HashSet<char> _quoters= ['"', '\''];
public HashSet<char> Quoters {
get {return this._quoters; }
set {
if (value.Intersect(this.Delimiters).Any())
{
throw new ArgumentException(CommonCharactersErrorMessage, nameof(this.Quoters));
}

this._quoters = [..value]; // create a copy!
}
}

/// <summary>
/// delimiters
/// default is space and tab
/// should contain at least one character. if empty will return the full string as single token
/// </summary>
public HashSet<char> Delimiters { get; set; } = [' ', '\t'];
private HashSet<char> _delimters= [' ', '\t'];
public HashSet<char> Delimiters { get { return this._delimters; }
set {
if (value.Intersect(this.Quoters).Any())
{
throw new ArgumentException(CommonCharactersErrorMessage, nameof(this.Delimiters));
}

this._delimters = [.. value]; // create a copy!

}
}

public static readonly HashSet<char> CsvDelimiters = [',', ';', '\t'];

/// <summary>
/// the delimiters typically used for CSV files
/// </summary>
public static readonly ImmutableHashSet<char> CsvDelimiters = [',', ';', '\t'];

public static IEnumerable<string> Split(
string source, HashSet<char> delimiters, HashSet<char>? quoters = null, bool treatConsecutiveDelimitersAsOne = false, bool treatTwoQuotesAsLiteral = false
Expand Down
5 changes: 5 additions & 0 deletions TestProject1/Test1.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,11 @@ public void TestMethodSingleDelimiter()
Assert.IsTrue(result[1].Length == 0);
}

[TestMethod]
public void TestMethodSingleCommon()
{
Assert.Throws<ArgumentException>(()=>new QuotedStringSplitter() { Delimiters = ['A','B'], Quoters=['A'] });
}


[TestMethod]
Expand Down