I need a regex that does the following replacements:
"\"Id\":\"123Abc\",\"foo\":\"bar\"" -> "\"Id\":null,\"foo\":\"bar\"" (change value for only field \"Id\" into null)
"\"Id\":123" -> "\"Id\":null" (works for numbers too)
"\"Id\":null" -> "\"Id\":null" (if already null, do nothing)
"\"foo\":\"bar\"" - > "\"foo\":\"bar\"" (if \"Id\" not present, do nothing)
I came up with \\\"Id\\\":([^]+), and on https://www.regextester.com it matches my string, but I tried turning it into Java code and nothing happens to the string.
str.replaceAll("\\\"Id\\\":([\\^]+)", "\\\"Id\\\":null");
\"is a delimiter, how do you check for an escaped delimiter ?Idcan be a string literal, that literal can contain escaped characters, so writing a regex is complex. What you should consider, more than performance, is correctness. A JSON parser will parse correctly. A regex may go wrong if there's some condition you forgot to check. Use a parser!! Don't waste more time on this, unless you learn thru profiling that performance is too slow. Beware premature optimizations, especially where optimizations may cause incorrect behavior.