Creating a regular expression to capture a numerical value enclosed by different characters:

export interface ValueParserResult {
  value: number, 
  error: string
}

interface subParseResult {
  result: (string | number) [], 
  error: string
}

class ValueParser {

  parse(eq: string, values: {[key: string] : number}, level?: number) : ValueParserResult {
    const result: ValueParserResult = { value: 0, error: "" }
  
    const numberRe: RegExp = /([^|\\(||/|/\\-|-|\\*|\\*\\-|+|\\^])+([0-9.]*)([$|(|)|/|/-|-|*|*-|+|])+/g;
          
    const eqParse = eq.split(" ").join('');
    eqParse.replace(numberRe, (matched) => {
      return " ," + matched;
    })
    
    console.log(eqParse)
    return result;

  }
}

const vp = new ValueParser();
const values = {x: 18, y:-3, z: 7}

const eq = "3452/132*67*(x+y/z)"

vp.parse(eq, values)

This snippet formats the eqParse data by adding a space and comma before each value instead of capturing surrounding strings.

Answer №1

There seems to be some confusion here:

  • The pipe | is not functioning as an OR-operator within the [ ] class, and you cannot match a sequence of multiple characters (like /-) in that type of regex class. Each character inside the [ ] is treated individually, and the class matches only one of them.

  • The replace method does not alter the original string it operates on. Also, strings are immutable in JavaScript. Therefore, you need to store the result of this operation in a new variable.

Below is the corrected section of your code:

const eq = "123/456*82*(a+b/c)";
// A regex pattern that can match alphanumerics (including periods) or non-alphanumerics:
const numberRe = /[\w.]+|[^\w.]+/g
// Assign the return value of the replace call to eqParse:
const eqParse = eq.replace(/ /g, "").replace(numberRe, (matched) => {
  return ", " + matched; // Did you mean to add a comma first?
}).slice(2); // Skip the first ", "

console.log(eqParse);

Answer №2

Updated regex pattern to extract numbers surrounded by other characters as shown below

const numberRe: RegExp = /(?<=[^\d.])\d+(?:\.\d+)?(?=[^\d.])/g;

I (geewhizbang) made a revision and shared it on a typescript playground:

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

Is it possible to submit a form through a JavaScript hotkey?

Here's the current code that I'm working with: <select tabindex="2" id="resolvedformsel" name="resolved"> <option selected="selected" value="yes">resolved</option> <option value="no">not resolved</option> ...

Transfer data via ajax to the controller

I need assistance with storing a file in my database using Tabulator without having a form already created. I am currently creating a simple input element like this: var editor = document.createElement("input");. After clicking the file, it trigg ...

Using a function from one class within another class by passing it as a prop

Below are the methods found in my Search.tsx class. renderSuggestion(suggestion) { <div className="buttons"> <button className="button">View Location</button> <button className="button whitebutton" onClick={this.h ...

Storing files offline in Firefox 3.5 with file:// protocol

While experimenting with the code for offline storage in Firefox 3.5, I referred to a tutorial on . When the page loads, I am prompted with a dialog asking to store data, but after clicking Allow, the dialog does not disappear. The application functions co ...

Accessing the observable's value by subscribing to it

There is a defined observable called imageOptions$ in my code: imageOptions$: Observable<BoundImagesToProject[]> = this.imagesService .getBoundImages({ projectId: this.projectId }) .pipe(map((images) => (images.data))); and it is used in the temp ...

Is there a way to implement a css/javascript property specifically for a div that is selected in the url?

Take for instance the scenario where I possess the URL example.com/#foo. In this case, CSS styling will be directed to the div with the id foo. If achieving this solely in CSS is not feasible, what methods in JavaScript or jQuery can be used efficiently ...

Adding and adjusting the size of different DIV elements within a shared area

Looking to create a dynamic bar with the ability to add multiple child DIVs (similar to this: https://i.stack.imgur.com/tdWsq.jpg). Utilizing jQuery, jQuery UI, Bootstrap, and various plugins. The structure for the div (or span) system could be structured ...

Is Jquery Mobile's Table lacking responsiveness?

I have implemented a basic table from the jQuery Mobile website on my page. Take a look at the HTML code below: <div data-role="page" id="mainPage"> <div data-role="content> <table data-role="table" id="my-table" da ...

In AngularJS, the execution of a subsequent AJAX call is reliant on the response of a preceding AJAX

Initially, I invoked the userSignupSubmit function. Within this method, another method called mobilenocheckingmethod is called. This method depends on the response from an AJAX call to make another AJAX call, but unfortunately, the second call does not w ...

Is it possible to save an entire webpage that infinitely scrolls without actually manually scrolling through it?

I'm dealing with a webpage that has infinite downward scrolling. I tried automating the scrolling, but eventually the page became too large to continue scrolling. To fix this, I manually removed some DIV blocks from the source code which decreased the ...

Transform a continuous string into an associative array with multiple dimensions

I am facing a challenge where I need to extract values from a string without any delimiting characters and create an associative array out of it. Let's take a look at an example string: *01the title*35the author*A7other useless infos*AEother useful i ...

Firefox not clearing Highcharts points properly

I am currently utilizing highcharts to generate dynamic charts when hovering over a table row. My goal is to clear and hide the chart once the mouse moves away from the row. While this functionality works smoothly in Chrome, I am encountering a strange is ...

Utilizing Javascript within a PHP while loop to showcase map markers

Is there a way to display multiple database entries in a loop and show them as markers on a map like this: https://i.stack.imgur.com/SwaGP.png I am struggling with looping through JavaScript in PHP to display multiple markers. Is it possible to achieve t ...

Adding elements to a JSON array in Javascript

Seeking assistance on updating a JSON array. var updatedData = { updatedValues: [{a:0,b:0}]}; updatedData.updatedValues.push({c:0}); This will result in: {updatedValues: [{a: 0, b: 0}, {c: 0}]} How can I modify the code so that "c" becomes part of ...

Error encountered during Jasmine unit testing for the ng-redux @select directive

Here is a snippet from my component.ts file: import { Component, OnInit } from '@angular/core'; import { select } from 'ng2-redux'; import { Observable } from 'rxjs/Observable'; import { PersonalDetailsComponent } from ' ...

I am trying to figure out how to send a One Signal notification from my Ionic app using the One Signal REST API. I have reviewed the documentation, but I am still unable to understand it

Is there a way to send a one signal notification from my ionic app using the one signal API? I have reviewed the documentation but am having trouble with it. While I have set up the service and it is functional, I can only manually send notifications thr ...

Non-IIFE Modules

Check out this discussion on Data dependency in module I have several modules in my application that rely on data retrieved from the server. Instead of implementing them as Immediately Invoked Function Expressions (IIFEs) like traditional module patterns ...

Is HTML-escaping necessary when implementing regex checks?

As I develop a web application that takes user input through HTML inputs and forwards it to my tomcat server for processing, my current workflow is as follows: Client JS -> collect HTML input -> perform regex validation -> if successful -> send data via ...

Leverage the power of Angular CLI within your current project

I am currently working on a project and I have decided to utilize the angular cli generator. After installing it, I created the following .angular-cli file: { "$schema": "./node_modules/@angular/cli/lib/config/schema.json", "project": { "name": " ...

What is causing the sorting table to fail in React when using useState?

import React, { useState } from "react"; import "./App.css"; const App = () => { const [data, setData] = useState([ { rank: 1, name: "John", age: 29, job: "Web developer", }, { rank: 2, name: "Micha ...