parsing string to extract key/value pairs

Currently, I am extracting key/value pairs from the body text of incoming emails.

Here is an example of an email body:
First Name: John
Last Name: Smith
Email : [email protected]
Comments = Just a test comment that
may span multiple lines.

I attempted to use a RegEx pattern ([\w\d\s]+)\s?[=|:]\s?(.+) in multiline mode. While this works for most emails, it fails when there is a line break within the value. My knowledge of RegEx is limited, so I seek further guidance.

Another approach I have taken involves parsing each line individually to locate key/value pairs, merging lines into the previous value if no pair is found. This method is written in Scala.

val lines = text.split("\\r?\\n").toList
var lastLabelled: Int = -1
val linesBuffer = mutable.ListBuffer[(String, String)]()

// only parse lines until the first blank line
// null_? method is checks for empty strings and nulls
lines.takeWhile(!_.null_?).foreach(line => {
  line.splitAt(delimiter) match {
    case Nil if line.nonEmpty => {
      val l = linesBuffer(lastLabelled)
      linesBuffer(lastLabelled) = (l._1, l._2 + "\n" + line)
    }
    case pair :: Nil => {
      lastLabelled = linesBuffer.length
      linesBuffer += pair
    }
    case _ => // skip this line
  }
})

I aim to utilize RegEx so that I can store the parser in the database and customize it for different senders at runtime (implementing various parsers for various senders).

Is it possible to modify my RegEx to recognize values containing newlines? Or should I abandon RegEx in favor of JavaScript? I already possess a JavaScript parser that allows me to save the JS in the DB and accomplish everything I want with the RegEx parser.

Answer №1

It seems like this solution will do the trick...

((.+?)((\s*)(:|=)(\s*)))(((.|\n)(?!((.+?)(:|=))))+)

...as shown in action on . By iterating through the matches, you should be able to extract both the key and value pairs.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I'm encountering an issue with my Angular CLI project where it's showing an error message that says "Module cannot be found."

Currently, I am diving into an Angular-cli tutorial. In one of my component TS files, there seems to be a problem with importing a class from another directory as it is not being recognized. Below is the content of my component file (display-user-data-for ...

What is the best way to redirect nodejs requests to a separate nodejs application?

Hello! I am currently working on a project to create an API gateway using Node.js and Express. The goal is to showcase a small-scale microservices architecture by routing requests to different microservices. For instance, if I have microservices A, B, and ...

"Selecting elements using the nth-of-type CSS selector alongside other

Dealing with a grid layout that includes spacers between certain items, I attempted to use the :nth-of-type selector in CSS to style only the first column of items and not apply those styles to the right side. However, it seems that the CSS gets confused w ...

Hide the content within a table row by setting the display to

I need to hide the div with the id "NoveMeses" if all h3 elements display "N.A." Is there a way to achieve this? If both h3 elements in row1 and row2 contain the text "N.A.", I want the div NoveMeses to be hidden. Below is the code snippet using AngularJ ...

Issue with highlighting when one string overlaps with another

I am facing a challenge with handling a string that contains Lorem Ipsum text. I have JSON data that specifies the start and end offsets of certain sections within the text that I need to highlight. The approach I am currently using involves sorting the JS ...

Prevent rapid event triggers with a jQuery slider

I am currently working with an event function in JavaScript that involves a slider and a tooltip element. Here is the code snippet: //Hide the Tooltip initially tooltip.hide(); //Initialize the Slider slider.slider({ ...

Choose a node from descendants based on its attribute

I am working with an interface that switches between displaying different div elements. Each div element has their children arranged differently, and when the switch happens, I need to access a specific child node of the newly displayed div. However, I fin ...

Quick question about utilizing Ajax with spans

<span name = "menu"> <!-- javascript here --> <!-- content loaded via ajax --> </span> <span name = "content"> <!-- content loaded via ajax --> <!-- updated by buttons from the menu--> </span> Seeking a ...

Customize chrome's default shortcuts with JavaScript

I'm working on an application that requires me to override some shortcut keys in the Chrome browser. While I'm able to create custom shortcuts to trigger alerts like in this Stackblitz example, I'm having trouble overriding a few default sho ...

Retrieve the nearest attribute from a radio button when using JQuery on a click event

I have a query regarding the usage of JS / JQuery to extract the data-product-name from a selected radio button, prior to any form submission. Although my attempt at code implementation seems incorrect: return jQuery({{Click Element}}).closest("form" ...

What are the best ways to gather value using javascript?

My Javascript array looks something like this below: [ { "id": 1, "facilities": [ { "id": 10, "name": "Wifi", "label": "Wifi" }, { "id": 12, "name": "Toll", "label": "Toll" ...

Including an anchor element with a specified URL, alongside passing the URL as a property

Having trouble passing a URL to href using a property. I'm attempting to pass the {props.github} value to href, but it's not working as expected. I've set up a property object with a field called github like this: export const projectList ...

Modifying Image Source on Hover Using Jquery

Is it possible to change the source of an image on hover and then back to the original source? For example, the name of the file always remains the same, but the number changes - 1 for the original and 2 for the hover. Thank you for any advice. Code: < ...

Is it possible to rotate an image with a random angle when hovering in Angular?

I'm currently working on a photo gallery project and my goal is to have the images rotate when hovered over. However, I am experiencing difficulties in passing values from TypeScript into the CSS. HTML <div class="back"> <div cl ...

Creating a spacious text box for an enhanced Ajax search feature

I'm currently working on an AJAX application that allows users to input the name of a movie, and then loads results from the database through jquery using a PHP API. However, I'm facing a challenge in implementing a text box with the following re ...

Having trouble figuring out how to sort an object array within a Vuex action in Vue.js

Currently attempting to sort an array, however, the sorting function doesn't seem to be working as expected based on the console log output. I'm puzzled as to why it's not executing properly. Interestingly, the same code runs fine in simple ...

What are the steps to set up auto-building with create-react-app?

I've been utilizing create-react-app for some time now. Autoreloading with 'npm start' or 'yarn start' has been working well on its own, but now I'm facing another issue. Currently, I am running the app on an Express server th ...

The routing functionality in Angular4 encounters issues when the `router.navigate()` method is used within the callback of a

I am currently working on implementing Google Sign In within my Angular4 app, but I have run into an unusual issue with routing after using router.navigate() in the Google Sign In callback function. To help illustrate this issue, I have created a sample d ...

Obtain the line break text from a given string

I am working with a string that looks like this: string=" (2021-07-04 11:58:43 PM BST) --- len (Tradition ) says to sen Hi yohan (2021-07-05 12:04:42 AM BST) --- len (Tradition) says to yohan okay -5 / 0 . (2021-07-04 11:47:14 PM BST) - ...

Query in progress while window is about to close

I'm attempting to trigger a post query when the user exits the page. Here's the code snippet I am currently working with: <script type="text/javascript> window.onbeforeunload = function(){ var used = $('#identifier').val(); ...