Skip to content

Instantly share code, notes, and snippets.

@sutra
Last active July 25, 2022 04:16
Show Gist options
  • Save sutra/da7cd596014cf555f1105e492192a15b to your computer and use it in GitHub Desktop.
Save sutra/da7cd596014cf555f1105e492192a15b to your computer and use it in GitHub Desktop.
String makeToJsonStr(String str) {
var keys = "label|fieldType|searchType|editHide|addHide|hide|disabled|required|comment|options";
var regex = "(?<key>" + keys + ")\\s*:(?<value>(?:(?!(" + keys + "):).)*)(?<delimiter>[\\,\\}])";
var replacement = "\"${key}\":\"${value}\"${delimiter}";
var replaced = str.replaceAll(regex, replacement);
return replaced;
}
@Test
void testMakeToJsonStr() {
var str = "{label :用户 id,searchType:1,hide:1,disabled:1,required:1,options:1:yes:tag-info,2:no:tag-danger}";
var replaced = makeToJsonStr(str);
var expected = """
{"label":"用户 id","searchType":"1","hide":"1","disabled":"1","required":"1","options":"1:yes:tag-info,2:no:tag-danger"}""";
assertEquals(expected, replaced);
}
@Test
void testMakeToJsonStr_keyInValueButDoesNotHaveColon_keyAfterOptionsValueAndHasColon() {
var str = "{label :用户 id,searchType:1,hide:1,disabled:1,required:1,options:1:yes:tag-info,2:no,fieldType,fieldType:tag-danger}";
var replaced = makeToJsonStr(str);
var expected = """
{"label":"用户 id","searchType":"1","hide":"1","disabled":"1","required":"1","options":"1:yes:tag-info,2:no,fieldType","fieldType":"tag-danger"}""";
assertEquals(expected, replaced);
}
@sutra
Copy link
Author

sutra commented Jul 24, 2022

package main

import (
	"testing"

	"github.com/dlclark/regexp2"
	"github.com/stretchr/testify/assert"
)

func TestMakeToJsonStr(t *testing.T) {
	keys := "label|fieldType|searchType|editHide|addHide|hide|disabled|required|comment|options"

	regex := "(?<key>" + keys + ")\\s*:(?<value>(?:(?!(" + keys + "):).)*)(?<delimiter>[\\,\\}])"
	replacement := "\"${key}\":\"${value}\"${delimiter}"

	re := regexp2.MustCompile(regex, 0)

	str := "{label  :用户 id,searchType:1,hide:1,disabled:1,required:1,options:1:yes:tag-info,2:no:tag-danger}"
	replaced, _ := re.Replace(str, replacement, -1, -1)
	assert.Equal(t, `{"label":"用户 id","searchType":"1","hide":"1","disabled":"1","required":"1","options":"1:yes:tag-info,2:no:tag-danger"}`, replaced)

	str = "{label  :用户 id,searchType:1,hide:1,disabled:1,required:1,options:1:yes:tag-info,2:no,fieldType,fieldType:tag-danger}"
	replaced, _ = re.Replace(str, replacement, -1, -1)
	assert.Equal(t, `{"label":"用户 id","searchType":"1","hide":"1","disabled":"1","required":"1","options":"1:yes:tag-info,2:no,fieldType","fieldType":"tag-danger"}`, replaced)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment