How do i remove a specefic character from a file?

匆匆过客 提交于 2019-12-13 07:47:24

问题


I have this JSON file in this format;

[{
"item-id" : "0",
"item-name" : "Dwarf remains",
"item-examine" : "The body of a Dwarf savaged by Goblins.",
"shop-value" : "0.0",
"low-alch" : "0.0",
"high-alch" : "0.0",
"stab-bonus" : "0",
"slash-bonus" : "0",
"crush-bonus" : "0",
"magic-bonus" : "0",
"ranged-bonus" : "0",
"stab-defence" : "0",
"slash-defence" : "0",
"crush-defence" : "0",
"magic-defence" : "0",
"ranged-defence" : "0",
"strength-bonus" : "0",
"prayer-bonus" : "0",
},
{
"item-id" : "1",
"item-name" : "Toolkit",
"item-examine" : "Good for repairing a broken cannon.",
"shop-value" : "0.0",
"low-alch" : "0.0",
"high-alch" : "0.0",
"stab-bonus" : "0",
"slash-bonus" : "0",
"crush-bonus" : "0",
"magic-bonus" : "0",
"ranged-bonus" : "0",
"stab-defence" : "0",
"slash-defence" : "0",
"crush-defence" : "0",
"magic-defence" : "0",
"ranged-defence" : "0",
"strength-bonus" : "0",
"prayer-bonus" : "0",
}]

But with 25 000 entries

But in the file there is something wrong;

"prayer-bonus" : "0",

should be

"prayer-bonus" : "0"

How can i use regex or whatever to only replace the last bit?

Im using java.

By the way: the value is not always "0"

So how can i have it be a wildcard so it replaces all ?


回答1:


You can use this (written in java style, to use with replaceAll() method):

search: (?<!\\\\)(\"(?>[^\\\"]++|\\\\{2}|\\\\.)*+\"),(\\s*+})
replace: $1$2

The main interest of this pattern is that you avoid escaped double quotes that may be inside quotes.

Example:

String pattern = "(?<!\\\\)(\"(?>[^\\\"]++|\\\\{2}|\\\\.)*+\"),(\\s*+})";
String result = yourJson.replaceAll(pattern, "$1$2");



回答2:


use sed:

sed -i.bak 's/\("prayer-bonus" : "0"\),/\1/' file

To match any number:

sed -i.bak 's/\("prayer-bonus" : "[0-9]*"\),/\1/' file



回答3:


It seems like you may be trying to patch a problem caused by improperly formed JSON blobs. You could take the other responder's answer of using sed to fix these symptoms but the problem lies in how the JSON is being created.




回答4:


Any text editor will do the trick.

Or you can call string replace from java. No need for regex.



来源:https://stackoverflow.com/questions/19959300/how-do-i-remove-a-specefic-character-from-a-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!