【C#】字符串按条件替换关键字
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | private string MyReplace( string json, string keyWord, string newWord, Func< string , string , bool > func) { StringBuilder sb = new StringBuilder(); int preIndex = 0; int oldLen = keyWord.Length; int lastIndex = json.LastIndexOf(keyWord); while ( true ) { int idx = json.IndexOf(keyWord, preIndex); if (idx < 0) { return json; } var temp = json.Substring(preIndex, idx - preIndex); sb.Append(temp); var temp1 = string .Empty; var temp2 = string .Empty; if (idx - 1 < 0) { temp1 = "" ; } else { temp1 = json.Substring(idx - 1, 1); } if (idx + oldLen >= json.Length) { temp2 = "" ; } else { temp2= json.Substring(idx + oldLen, 1); } if (func(temp1,temp2)) { sb.Append(newWord); } else { sb.Append(keyWord); } preIndex = idx + oldLen; if (preIndex > lastIndex) { break ; } } if (preIndex < json.Length) { sb.Append(json.Substring(preIndex)); } return sb.ToString(); } |
测试代码:
1 2 3 4 5 | string json = "\"abc\"{\"abc\":\"13\",\"jeabcje\":23,\"jabc\":234,\"abcJ\":567,\"a13\":323,\"ggg\":\"end\"}\"abc\":12abc3" ; string keyWord = "abc" ; string newWord = "Keys" ; string str = MyReplace(json, keyWord, newWord, (a, b) => { return a == "\"" && b == "\"" ; }); |
主要功能是把json里 属性替换掉,比如"abc"属性 替换成“Keys”,而不会把“jeabcje”这种包含abc的属性也替换为Key。
func是你的特殊条件,当满足这个条件,才会替换关键字。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步