正则表达式用于为字符串值添加引号

huangapple go评论57阅读模式
英文:

regular expression to add quotes for string values

问题

我试图仅为文件中的**字符串**值添加引号,例如:

String content = "ids:["123"],name:null,Quantity:8d-1,number:123,name:"hello",id2:"1234"";


对于 `ids`,因为它是一个数组,所以没问题。`name` 为空,所以也没问题。`Quantity` 需要在其值上加引号,`number` 的值是数字,所以也没问题。所期望的输出是

"ids:["123"],name:null,Quantity:"8d-1",number:123,name:"hello",id2:"1234"";


我写了以下代码

content.replaceAll(":([^"]+),", ":"$1",");


但这并没有给我正确的结果。任何帮助都将不胜感激!谢谢
英文:

I'm trying to add quotes for string values only in a file, for example:

String content = "ids:[\"123\"],name:null,Quantity:8d-1,number:123,name:\"hello\",id2:\"1234\""; 

for ids, since it's an array, so it's fine. name is null so it's also good. Quantity needs quotes on its value, number is good as its value is digit. So the expected output is

"ids:[\"123\"],name:null,Quantity:"8d-1",number:123,name:\"hello\",id2:\"1234\""; 

I wrote

content.replaceAll(":([^\"]+),", ":\"$1\",");

but which does not give me correct result. Any help is appreciated! Thanks

答案1

得分: 1

user8142520,您编写的方式会替换掉name之后的所有内容,由于默认是贪婪模式,它会获取最长的匹配,这仅发生在number之后的逗号处。

name字段与您的正则表达式不匹配,因为其中有双引号。

我假设Quantity字段可以具有与其他字段内容分隔的任何模式。

因此,在您的正则表达式之前,我添加了y,以限制在Quantity字段上的替换范围,并且我在正则表达式中将[^\"]替换为[^,],以便匹配范围不会侵入其他字段。

content.replaceAll("y:([^,]+),", "y:\"$1\",")
英文:

user8142520, the way you wrote it replaces everything that comes after name, and since the default is greedy, it gets the longest fit, which only happens at the comma after number.

The name field doesn't fit your regex because of double quotes in it.

I've assumed that the Quantity field can have any pattern that can be separated from the content of other fields.

So I add y before your regex, to limit the replacing scope on the Quantity field and I've replaced in the regex [^\"] for [^,], so the fit range doesn't invade other field.

content.replaceAll("y:([^,]+),", "y:\"$1\",")

huangapple
  • 本文由 发表于 2020年7月30日 13:33:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/63166783.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定