Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

String parsing analyzer to replace regex split, enables ^CC and ^CT commands #189

Merged
merged 3 commits into from
Sep 18, 2023
Merged
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
59 changes: 55 additions & 4 deletions src/BinaryKits.Zpl.Viewer/ZplAnalyzer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Application.UseCase.ZplToPdf;

Expand Down Expand Up @@ -121,14 +122,64 @@ public AnalyzeInfo Analyze(string zplData)

private string[] SplitZplCommands(string zplData)
{
if (string.IsNullOrEmpty(zplData))
if (string.IsNullOrWhiteSpace(zplData))
{
return Array.Empty<string>();
}

var replacementString = string.Empty;
var cleanZpl = Regex.Replace(zplData, @"\r\n?|\n", replacementString);
return Regex.Split(cleanZpl, "(?=\\^)|(?=\\~)").Where(x => !string.IsNullOrEmpty(x)).ToArray();
var cleanZpl = Regex.Replace(zplData, @"\r|\n", string.Empty);
char caret = '^';
char tilde = '~';
List<string> results = new(200);
StringBuilder buffer = new(2000);
for (int i = 0; i < cleanZpl.Length; i++)
{
char c = cleanZpl[i];
if (c == caret || c == tilde)
{
string command = buffer.ToString();
buffer.Clear();
if (command.Length > 2)
{
PatchCommand(ref command, ref caret, ref tilde);
results.Add(command);
if (command.Substring(1, 2) == "CT")
{
tilde = command[3];
results.RemoveAt(results.Count - 1);
}
else if (command.Substring(1, 2) == "CC")
{
caret = command[3];
results.RemoveAt(results.Count - 1);
}
}
// likely invalid command
else if (command.Trim().Length > 0) {
results.Add(command.Trim());
}
}
buffer.Append(c);
}
string lastCommand = buffer.ToString();
if (lastCommand.Length > 0)
{
PatchCommand(ref lastCommand, ref caret, ref tilde);
results.Add(lastCommand);
}
return results.ToArray();
}

private void PatchCommand(ref string command, ref char caret, ref char tilde)
{
if (caret != '^' && command[0] == caret)
{
command = '^' + command.Remove(0, 1);
}
if (tilde != '~' && command[0] == tilde)
{
command = '~' + command.Remove(0, 1);
}
}
}
}
Loading