utilizing regular expressions to retrieve data

I am facing a challenge in extracting both the product name and price from the given data. The desired result, which includes both the product name and price, is not on the same line. How can I include the line that comes before the price as well?

Here is a sample structure of a product from a receipt:

RETAIL
UPRICE QTY TOTAL
ILLUSTRATION BOARD 15X20 (1/4 SIZE ) BY
1276
12.50 1.0 12.50
MONGOL PENCIL 1,2,3 PC
434
6.50 1.0 6.50
MS 300 (MGK) PERMANENT MARKER
1470
3.75 1.0 3.75
HBW White Glue 40 grans
1690
10.00 1.0 10.00
COLOR PEN 8 COLORS (VARIOUS BRAND)
1930
16.50 1.0 16.50
KS /CREATION CONSTRUCTION PAPER (105)
3503
23.00 1.0 23.00

I have attempted to use the following regex to solve the issue, but the result only displays the price without including the product name. The 'result' variable contains data similar to the sample provided above.

TypeScript file code snippet:

   this.result = {
      merchant: text.split("\n")[0],
      product: text.split("\n").filter(t => t.match(/([\w\s]+)(\d+\.\d{2})/)
   };

HTML file code snippet:

 <ion-card *ngIf="result">
    <ion-card-content>
      <p>Results:</p>
      <ion-item>
        <ion-label>Merchant</ion-label>
        <ion-input type="text" value="{{result.merchant}}"></ion-input>
      </ion-item>
      <ion-item *ngFor="let product of result.product; let i = index">
        <ion-label>Product #{{i+1}}</ion-label>
        <ion-input type="text" value="{{product}}"></ion-input>
      </ion-item>
    </ion-card-content>
  </ion-card>

Answer №1

If you want to extract the price from a text by capturing any character followed by a newline and then the price itself, you can use the following regex pattern:

(.+\n.+\n)(\d+\.\d{1,2})

Check out the Regex demo here

Here's the breakdown of the regex pattern:

  • (.+\n.+\n) This part captures 2 sequences of 1 or more characters followed by a newline
  • (\d+\.\d{1,2}) This part captures the price format with digits before and after the dot

You can test this regex pattern on a sample text like the one below:

const regex = /(.+\n.+\n)(\d+\.\d{1,2})/g;
let products = [];

// Sample text for testing
let str = `RETAIL
UPRICE QTY TOTAL
ILLUSTRATION BOARD 15X20 (1/4 SIZE ) BY
1276
12.50 1.0 12.50
MONGOL PENCIL 1,2,3 PC
434
6.50 1.0 6.50
MS 300 (MGK) PERMANENT MARKER
1470
3.75 1.0 3.75
HBW White Glue 40 grans
1690
10.00 1.0 10.00
COLOR PEN 8 COLORS (VARIOUS BRAND)
1930
16.50 1.0 16.50
KS /CREATION CONSTRUCTION PAPER (105)
3503
23.00 1.0 23.00`;

while ((m = regex.exec(str)) !== null) {
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    products.push([m[1].replace(/\n/g, ''), m[2]]);
}

console.log(products);

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

Typescript's ability to have Enums with dynamic keys

Suppose I define: enum Sort { nameAsc = 'nameAsc', nameDesc = 'nameDesc' } Is it possible to do the following? const key = 'name' + 'Desc'; Sort[key] Appreciate any help in advance ...

What is the best way to modify the disabled attribute?

After disabling a button using a boolean variable, updating the variable does not remove the disabled attribute. How can I update my code to enable the button when the variable changes? Here is my current code snippet: var isDisabled = true; return ( ...

Error: Model attribute missing in Adonis JS v5 relationship

Recently, I started diving into the Adonis framework (v5) and decided to build a todo list api as part of my learning process. However, I'm facing an issue concerning the relationship between the User and Todo entities. Let me show you the models fo ...

Executing a component method from a service class in Angular

When trying to call a component method from a service class, an error is encountered: 'ERROR TypeError: Cannot read property 'test' of undefined'. Although similar issues have been researched, the explanations mostly focus on component- ...

Guide on dynamically applying a CSS rule to an HTML element using programming techniques

Currently working with Angular 6 and Typescript, I am facing a unique challenge. My task involves adding a specific CSS rule to the host of a component that I am currently developing. Unfortunately, applying this rule systematically is not an option. Inste ...

Troubleshooting problem with TypeScript observables in Angular 5

Having trouble with a messaging app, specifically an error related to TS. The syntax checker in the Editor is flagging this issue: Type 'Observable<{}>' is not compatible with type 'Observable'. Type '{}' cannot be as ...

The attempt to upload a file in Angular was unsuccessful

Below is the backend code snippet used to upload a file: $app->post('/upload/{studentid}', function(Request $request, Response $response, $args) { $uploadedFiles = $request->getUploadedFiles(); $uploadedFile = $uploadedFiles[&apo ...

The count of bits is not producing the anticipated result

Attempting to tackle the challenge of Counting Bits using JavaScript, which involves determining the number of set bits for all numbers from 0 to N, storing them in an array, and returning the result Let me provide an explanation Input: n = 5 ...

Array of dynamically typed objects in Typescript

Hello, I am a newbie to Typescript and I recently encountered an issue that has left me stumped. The problem I am facing involves feeding data to a Dygraph chart which requires data in the format [Date, number, number,...]. However, the API I am using prov ...

Why does React redirect me to the main page after refreshing the page, even though the user is authenticated in a private route?

In the process of developing a private route component that restricts unauthenticated users and redirects them to the homepage, we encountered an issue upon page refresh. The problem arises when the current user variable momentarily becomes null after a ...

Creating a JSX syntax for a simulated component and ensuring it is fully typed with TypeScript

Looking for some innovative ideas on how to approach this challenge. I have a test helper utils with added types: import { jest } from '@jest/globals' import React from 'react' // https://learn.reactnativeschool.com/courses/781007/lect ...

Issue encountered during frida-il2cpp-bridge module installation

Having trouble with installing the frida module (frida-il2cpp-bridge)? I followed the steps, but encountered errors. You can check out the installation steps here. The specific error message I received is: Spawned `com.games`. Resuming main thread! Refe ...

Exploring Angular Unit Testing: A Beginner's Guide to Running a Simple Test

I'm diving into the world of angular unit testing and looking to set up my first successful test. Here's what I've come up with: import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { AppComponent } fro ...

After each save, gulp-typescript is emitting errors, however, it works without any issues upon subsequent saves

I'm facing some uncertainty regarding whether the issue I'm encountering is related to gulp, typescript, or Angular 2. Currently, I am using Angular 2 Beta 6. Here is an example of my typescript gulp task: var tsProject = p.typescript.createPr ...

Can you explain the significance of this code snippet 'true <=> false'?

Today I came across this piece of code: true <=> false. I'm a bit confused by it and don't really understand how it works. If anyone could shed some light on this expression for me, I would greatly appreciate it. For reference, this code ...

Tips on informing the TS compiler that the value returned by a custom function is not null

There might be a way to make this code work in TypeScript, even though it's currently showing some errors regarding possible undefined values. Take a look at the code snippet: const someArray: foo[] | null | undefined = [...] // TS fail: someArray ...

Tips on personalizing the FirebaseUI- Web theme

Can someone help me find a way to customize the logo and colors in this code snippet? I've only come across solutions for Android so far. if (process.browser) { const firebaseui = require('firebaseui') console.log(firebaseui) ...

Module 'serviceAccountKey.json' could not be located

I'm encountering an issue while trying to incorporate Firebase Functions into my project. The problem lies in importing the service account key from my project. Here is a snippet of my code: import * as admin from 'firebase-admin'; var ser ...

Why is it advantageous to use Observable as the type for Angular 5 component variables?

Being a beginner in Angular 6, I have been exploring the process of http mentioned in this link: https://angular.io/tutorial/toh-pt6#create-herosearchcomponent One thing that caught my attention was that the heroes array type is set to Observable in the ...

The dramatist strategically positioning the cursor at the conclusion of an input field

Currently, I am utilizing playwright for my testing purposes and have encountered a specific issue that I am seeking assistance with. The behavior I need to test is as follows: Applying the bold style to existing text within my input field Verifying that ...