Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex replace everything not starting with multiple times in line

I am making a parser of sorts in javascript that takes a mathematical expression given to the script as a string, and evaluates it and does some other things with it. If the users want to use builtin Javascript mathematical functions, they have to enter the following string e.g. "1 + Math.log(x)". That becomes very tedious when things get nested e.g "Math.abs(Math.log(Math.pow(x, 2))) + Math.log2(x)". As you can see, the "Math." part of it not only takes longer to write, but makes it less readable. I want to remove that "Math." part. The way I've done it is using simple regex that basically has a list of all Javascript Math constants and methods and simply prepends the "Math." part of it. Simple enough:

  input = input.replace(/(E|PI|SQRT2|SQRT1_2|LN2|LN10|LOG2E|LOG10E)/g, "Math.$1");

The same things happens for the methods. This works fine. But as always that's not very flexible and leaves room for misunderstanding and somebody may coma along and insist on typing Math.log(x) which will in turn be replaced with Math.Math.log(x), which won't work.

What I want to know is, is there some way to match any of these predefined strings (constants and methods) so that they will only be matched via regex if they don't have the "Math." part in front of it. I have tried this

^(?!Math\.)(log2|log|exp|abs)

but it is quite useless, as this doesn't work with nesting and even multiple operands. Is there any way to do this purely in regex, as this would make the entire process more elegant. Any help would be appreciated.

like image 631
Pavlin Avatar asked May 27 '15 20:05

Pavlin


People also ask

What does ?= * Mean in regex?

Save this question. . means match any character in regular expressions. * means zero or more occurrences of the SINGLE regex preceding it. My alphabet.txt contains a line abcdefghijklmnopqrstuvwxyz.

What does \+ mean in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" .

What is regex multiline mode?

Multiline option, or the m inline option, enables the regular expression engine to handle an input string that consists of multiple lines. It changes the interpretation of the ^ and $ language elements so that they match the beginning and end of a line, instead of the beginning and end of the input string.

What is the difference between \b and \b in regular expression?

Using regex \B-\B matches - between the word color - coded . Using \b-\b on the other hand matches the - in nine-digit and pass-key .


1 Answers

You can use the following trick so that it gets replaced even if it matches or not:

(?:Math\.)?(log2|log|exp|abs|pow)

And replace with Math.$1

See DEMO

like image 93
karthik manchala Avatar answered Nov 10 '22 00:11

karthik manchala