Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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