skip to Main Content
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 = {a: 22, b:-10, c: 5}

const eq = "123/456*82*(a+b/c)"

vp.parse(eq, values)

This captures the entire eqParse string and puts a space comma in front of it. I want to put the comma space before each value and not capture the strings before and after.

3

Answers



  1. Modified regex to capture numbers surrounded by other characters below

    const numberRe: RegExp = /(?<=[^d.])d+(?:.d+)?(?=[^d.])/g;
    
    Login or Signup to reply.
  2. There are a few misunderstandings here:

    • The pipe | is not an OR-operator when used inside a [ ] class, nor can you match a sequence of more than one character (like /-) in such a regex class. All characters inside an [ ] are treated as separate characters and that class matches exactly one of them.

    • The replace method does not mutate the string it is called on. Moreover, strings are immutable in JavaScript. So you should assign the result of this call to your variable.

    Here is a correction of the relevant part of your code:

    const eq = "123/456*82*(a+b/c)";
    // A regex that either matches alphanumericals (and point) or non-alphanumericals (and not point):
    const numberRe = /[w.]+|[^w.]+/g
    // Use the return value of the replace call to assign it to eqParse:
    const eqParse = eq.replace(/ /g, "").replace(numberRe, (matched) => {
      return ", " + matched; // I think you intended to have the comma first?
    }).slice(2); // To skip the first ", "
    
    console.log(eqParse);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search