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
I posted your change at a typescript runner:
https://www.typescriptlang.org/play?module=1#code/JYOwLgpgTgZghgYwgAgGpwDYFcIAU5QDO0AShIVhmMgN4BQyyAbpjgFzIhYC2ARtABpkDZNCgB7KB0JgooAOZ0AvnTqhIsRCgq98RCGQpVaIqOUpgOAChlyQ85AB9OPflACUyANoBdISLFJaVkFZVUEDDhCQjRWPAJiKBMRAAcEiCsIAEdgu3khFmxyDhovAGsIAE9chR9kDi4+aCUhDAgmCAwAfgbXaE8OdCK9RMMLE0ZGBHEQGWQzI0tY4fSoMeMAXlpmOI4ABiFAqWQAIhPkFUmRKZm5xrcyDjJ5AFEADxTkLYB6Ky6AHg2XgAegAdAAmADofO4IQBqP5sUGQ+HuLp-IFgqEw77yADc10YhLa1GyIxQW2ykMIKQwwDAVnOJ3ckIAVuJQFYAORc9wEyaiLLkr6C8mQsy0rRWe6kCBCKzcOBgBAACwg4M8GwAfBMBchprNxG1IRhxPIFUrVer3ITGGYwFgoCBTsgBOc4chFcq1eD+ZMlDaBYSDYQjRATWbMkL0oHJvbHc6FhYCSIVCo6CHqExPlsQBAAO7LHDkqBWPkZ25ZuIxLY0OAcABMDaEvDYAFoAIwHfUcACs6czgpFJw7DYAzN8ACyQ3sANgAVAAOBvzqxwOG8b4IdwnVTZyFpfRRgrVm1AA
which returns the correct result in the console.log
Modified regex to capture numbers surrounded by other characters below
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: