Home > Software engineering >  How i can create a Regular Expression to return (0/00/00, 00:00, myName, message) from '0/00/00
How i can create a Regular Expression to return (0/00/00, 00:00, myName, message) from '0/00/00

Time:05-12

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:

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"
}

CodePudding user response:

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]))
}
  • Related