Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How i can create a Regular Expression to return (0/00/00, 00:00, myName, message) from '0/00/00, 00:00 – myName: my message'?

I’m creating a app to transform whatsapp backup .txt into a .json and .csv files.

My app it’s working but i am refactoring now.

This code snippet currently solves my problem using js:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

function stringToObject(string) {
    let commaSepareted = string.split(',')
    let date = commaSepareted[0]
    if(commaSepareted.length >= 2){

        let hyphenSepareted = commaSepareted.filter((_, index) => index >= 1).join().split('-')
        let time = hyphenSepareted[0].trimEnd().trimStart()

        let twoPointsSepareted = hyphenSepareted.filter((_, index) => index >= 1).join().split(':')
        let username = twoPointsSepareted[0].trimEnd().trimStart()
        let message = twoPointsSepareted.filter((_, index) => index >= 1).join()

        return {
            date,
            time,
            username,
            message
        }
    }
    return null
}

I want to refactor to resolve the same problem but using REGEX, so i basically need a function the receive a string in this format: "0/00/00, 00:00 – myName: message" and return a object like this:

{
    "date": "0/00/00",
    "time" : "00:00",
    "username": "myName",
    "message": "message"
}

>Solution :

Javascript happens to have a powerful Date constructor, which can parse and return much of the data you want. However, you you can also use regular expressions for this purpose. I quickly wrote one up that may work for your purposes: /(\d+\/\d+\/\d+), (\d+:\d+) - (\w+): (.*)/i, which, in code, looks like this: str.match(/(\d+\/\d+\/\d+), (\d+:\d+) - (\w+): (.*)/i)

To process that into your object format, you’d need a small parser function:

function parseData(inp) {
  let keys = ["date","time","username","message"]
  return Object.fromEntries(inp.match(/(\d+\/\d+\/\d+), (\d+:\d+) - (\w+): (.*)/i).slice(1).map((n,i)=>[keys[i],n]))
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading