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

What is the best way to adjust the size of an image as I navigate down a webpage?

I've been working on designing a navigation bar for a website, but I'm running into some issues. My goal is to have the logo shrink as the user scrolls down the site. I've experimented with webkit animations and various javascript/jQuery fun ...

Get a subsection of the array starting from index N up to the final

Is there a way to accomplish this specific transformation? ["a","b","c","d","e"] // => ["c", "d", "e"] I initially thought that using the slice method could work, however.. ["a","b","c","d","e"].slice(2,-1) // [ 'c', 'd' ] ["a","b ...

What is the best method for displaying a radio button as selected based on a variable value?

I have a variable that stores the value of a radio button. After checking certain conditions, I want to dynamically select the radio button based on this value. if(cheque_date == system_date) { cheque_value='Current'; } else { cheque_value ...

What is the best way to incorporate the skrollr-body tag without altering the overall height of the

Skrollr has been a game-changer, so thank you to the geniuses behind it. I made sure to properly place the skrollr-body tag around all elements except for the fixed background in order to make it work on mobile. However, I'm noticing that it is cutti ...

When the page is scrolled, the div is fixed in place and a class is dynamically added. Some issues may

Greetings everyone, I have a webpage with two floating divs - one is about 360px wide and the other has an auto width. As the page scrolls, the left div is assigned a class that fixes it to the screen, allowing the other div to scroll. This functionality w ...

iterating over a large multidimensional array in JavaScript

I am facing a challenge with handling a large JSON dataset (around 20k+ entries, totaling over 2mb) that I need to display on my web pages. Currently, I fetch this data using AJAX and parse it using JSON.parse in JavaScript, resulting in a complex multidi ...

Avoiding the use of numbers in v-if in Vue.js

My website features a left menu that displays different content based on the selected menu's ID. However, I currently have === 0 and === 1 in the v-if statement, and I'm looking for a way to avoid manually inputting these numbers. <template& ...

Place a Three.js scene within a jQuery modal dialogue box

I am attempting to integrate a Three.js scene into a jQuery modal window. The objective is to utilize the Three.js scene in a larger window size. This scene should be displayed after clicking on an image that represents the scene in a smaller dimension. Y ...

Querying MongoDB to locate an element within an array is a common task

I need help with writing a mongoose query to select a specific object from the "cartItems" array in my mongodb database and update its "qty" and "price" fields. Here is the data: { _id: new ObjectId("634a67e2953469f7249c9a7f"), user: new ObjectId("634 ...

Getting the Angular component class reference within a triggered Highcharts selection event callback - what's the best approach?

It seems like I'm facing a common javascript closure issue, but let me illustrate it with a specific example as I'm struggling to grasp it in an Angular context. In my Angular component, I'm using the Highcharts library to visualize data. W ...

Reversing the sequence of code in JavaScript - react native

I'm currently working on tracking the number of times a button is pressed within one second. For the most part, it's functioning correctly as it tracks and displays the count. The issue arises when it displays the button press count from the pr ...

What is the best way to create a screen capture of a webpage using a URL?

Currently working on a Spring MVC website project, I have implemented a form requesting the user's website URL. Once entered, I aim to display a screenshot of the specified website for the user to view. Contemplating whether to generate the image on ...

Is there a way to split a JSON string into an array using JQuery?

I need help splitting all the values from a JSON format string into an array. [{ "sno": "1", "code": "bp150mb", "quantity": null, "name": "mudguard", "company": "bajaj", "vehicle": "pulsar", "brand": "1", "image": "N/A", "color": "Blac ...

What could be causing the import alias issue in the latest version of Next.js, version 12

Below are my CompileOptions: { "compilerOptions": { "target": "es5", "lib": ["dom", "dom.iterable", "esnext"], "allowJs": false, "skipLibCheck": tr ...

Display JSON content in a div depending on the selected option value

Seeking a more efficient way to load data from a JSON file based on the user-selected option. Currently, I am using multiple else if statements for each state, but it feels repetitive and cumbersome. Is there a better approach? Here's a snippet of my ...

What is the method to access and examine the attributes of a range in Office.js?

I am encountering an issue while attempting to retrieve the values from cell B2 and create a conditional statement based on those values. Despite my efforts, I continue to receive an error message without any clear understanding of its cause. Please refe ...

Transferring data from client to server: Weighing the pros and cons of

When dealing with 1-5 variables on the client side that need to be sent to the server using AJAX (Post Method), there are two primary methods of getting them there. One option is to use JSON to encode and decode the variables, sending them as a JSON stri ...

jQuery: A variety of ways to close a div tag

I am encountering some difficulties trying to make this work properly, any assistance would be highly appreciated. The goal is to have the div close when the user clicks the X button, as well as when they click outside of the wrapper container. Unfortuna ...

Remove all stored data from localStorage and update the view in Backbone framework

Hi, currently I am using backbone localstorage and facing an issue where I need to clear the localstorage every time a user hits the search button. This will allow me to add new data to the localStorage without any conflicts. Additionally, I am attempting ...

How do I convert the object value/data to lowercase in JavaScript using underscore for an HTML5 document?

I am working with an array of objects (arr) where each object consists of 3 properties (Department, Categories, ProductTypes). The values for these properties are a mix of upper and lower case. To perform a comparison between arr and a search filter (alrea ...