diff --git a/stringutil/replace.go b/stringutil/replace.go new file mode 100644 index 0000000..5047b5f --- /dev/null +++ b/stringutil/replace.go @@ -0,0 +1,20 @@ +package stringutil + +import ( + "fmt" + "regexp" +) + +// ReplaceJSONField 使用正则表达式替换 JSON 字符串中指定字段的值 +// fieldNames: 要替换的多个字段名,使用竖线(|)分隔(例如:"tenantId|tenant_id") +// newValue: 新的值(字符串形式,将被包装在引号中) +// jsonStr: 原始 JSON 字符串 +func ReplaceJSONField(fieldNames, newValue, jsonStr string) string { + // 构建正则表达式模式 + // 匹配模式: ("field1"|"field2"|...): "任意值" + pattern := fmt.Sprintf(`(?i)("(%s)")\s*:\s*"([^"]*)"`, fieldNames) + re := regexp.MustCompile(pattern) + + // 替换匹配到的内容 + return re.ReplaceAllString(jsonStr, fmt.Sprintf(`${1}: "%s"`, newValue)) +} diff --git a/stringutil/replace_test.go b/stringutil/replace_test.go new file mode 100644 index 0000000..bcbb310 --- /dev/null +++ b/stringutil/replace_test.go @@ -0,0 +1,38 @@ +package stringutil + +import ( + "github.com/stretchr/testify/assert" + "testing" +) + +func TestReplaceJSONField(t *testing.T) { + // 测试替换单个字段 + jsonStr := `{"tenantId": "123", "name": "test"}` + result := ReplaceJSONField("tenantId", "456", jsonStr) + expected := `{"tenantId": "456", "name": "test"}` + assert.Equal(t, expected, result) + + // 测试替换多个字段 + jsonStr = `{"tenantId": "123", "tenant_id": "789", "name": "test"}` + result = ReplaceJSONField("tenantId|tenant_id", "456", jsonStr) + expected = `{"tenantId": "456", "tenant_id": "456", "name": "test"}` + assert.Equal(t, expected, result) + + // 测试字段不存在 + jsonStr = `{"name": "test"}` + result = ReplaceJSONField("tenantId", "456", jsonStr) + expected = `{"name": "test"}` + assert.Equal(t, expected, result) + + // 测试空 JSON 字符串 + jsonStr = `` + result = ReplaceJSONField("tenantId", "456", jsonStr) + expected = `` + assert.Equal(t, expected, result) + + // 测试空字段名 + jsonStr = `{"tenantId": "123"}` + result = ReplaceJSONField("", "456", jsonStr) + expected = `{"tenantId": "123"}` + assert.Equal(t, expected, result) +} diff --git a/tag.bat b/tag.bat index f936e2d..a3e8135 100644 --- a/tag.bat +++ b/tag.bat @@ -1,4 +1,4 @@ -git tag v1.1.20 +git tag v1.1.21 git tag bank_card/v1.1.5 git tag geoip/v1.1.5