Skip to content

Commit

Permalink
Improve json detection for formatted text (#1309)
Browse files Browse the repository at this point in the history
Signed-off-by: Pablo Herrera <[email protected]>
  • Loading branch information
Pablete1234 authored Apr 12, 2024
1 parent ffd116e commit aa50c40
Showing 1 changed file with 5 additions and 2 deletions.
7 changes: 5 additions & 2 deletions util/src/main/java/tc/oc/pgm/util/text/TextParser.java
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,9 @@ private TextParser() {}
private static final Pattern INF = Pattern.compile("^((\\+|-)?oo)$", Pattern.CASE_INSENSITIVE);
private static final Pattern DOT = Pattern.compile("\\s*\\.\\s*");
private static final Pattern COMMA = Pattern.compile("\\s*,\\s*");
// [{ "prop" : ... }], {prop: ...} or ['prop': ...}, looks like json, but could be invalid
private static final Pattern PROBABLY_JSON =
Pattern.compile("[\\[{][ \\[{]*\\s*([\"']?)\\w+\\1\\s*:.*[\\[}]+", Pattern.CASE_INSENSITIVE);
private static final Range<Integer> NONNEG = Range.atLeast(0);

/**
Expand Down Expand Up @@ -413,7 +416,7 @@ public static LocalDate parseDate(String text) throws TextException {
public static Component parseComponent(String text) throws TextException {
assertNotNull(text, "cannot parse component from null");

if (text.startsWith("{\"") && text.endsWith("\"}")) {
if (PROBABLY_JSON.matcher(text).matches()) {
try {
return GsonComponentSerializer.gson().deserialize(text);
} catch (JsonSyntaxException e) {
Expand Down Expand Up @@ -444,7 +447,7 @@ public static Component parseComponent(String text) throws TextException {
public static Component parseComponentSection(String text) {
assertNotNull(text, "cannot parse component from null");

if (text.startsWith("{\"") && text.endsWith("\"}")) {
if (PROBABLY_JSON.matcher(text).matches()) {
try {
return GsonComponentSerializer.gson().deserialize(text);
} catch (Throwable t) {
Expand Down

0 comments on commit aa50c40

Please sign in to comment.