0

Trying to create a function that will Append content to lines in a file that match a certain regex condition

AccountFile.txt

1    {
2        "account": "123456",
3        "MoreAccounts": { //Some-Comment-1
4            "evenMoreAccounts: {
5                "Hello" : "World"
6             } 
7        }
8    }

So if the regex to match is .*Some-Comment-1 it will match the 3rd line. And For example say I wanted to insert the text

"anotherAccount" : {
    "HelloWorld" : "2"
},

under the line that matches the regex above, the output of my program should be:

1    {
2        "account": "123456",
3        "MoreAccounts": { //Some-Comment-1
4             "anotherAccount" : {
5                "HelloWorld" : "2"
6             },
7            "evenMoreAccounts: {
8                "Hello" : "World"
9             }
10        }
11    }

The problem Im facing is the formatting, how can I make sure the text I want to insert always matches the surrounding text's formatting for any file extension .py, .yaml, .txt, .json, .java

Right now my function is outputting something that looks like this

1    {
2        "account": "123456",
3        "MoreAccounts": { //Some-Comment-1
4 "anotherAccount" : {
5     "HelloWorld" : "2"
6  },
7            "evenMoreAccounts: {
8                "Hello" : "World"
9             }
10        }
11    }

Is there any good external library that can do this for me? All help would be appreciated thanks

Or Even a Java Library that could beautify any text file would be useful

The programming language im using to write this is Java, so a java function or library would be helpful

Things Ive looked into

  • JAlopy ~ only works for java
chid00
  • 53
  • 4
  • You could concoct something by reading the file into a `List` of lines and then doing an insertion on match. That looks suspiciously like json though - or is that just accidental? – g00se Jul 16 '21 at 17:11

1 Answers1

1

Java has libraries supporting many various data formats, such as JSON, XML, YAML, and many more. There is no automatic option to guess the data format and insert the text under the right node based on the file extension. The example you've provided looks like JSON, for that you can use the Gson library. It is better to find the element you're looking for and insert your target element using the library's API than to parse pure text or use regex for this.