Skip to content

Commit

Permalink
Merge pull request #189 from reportingissue/string-parsing-analyzer
Browse files Browse the repository at this point in the history
String parsing analyzer to replace regex split, enables ^CC and ^CT commands
  • Loading branch information
YipingRuan authored Sep 18, 2023
2 parents b3ff852 + f326c5d commit 1353cae
Showing 1 changed file with 55 additions and 4 deletions.
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 @@ -122,14 +123,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);
}
}
}
}

0 comments on commit 1353cae

Please sign in to comment.