Regular expression for implementing an even-odd negative sign rule

I want to write a .replace function in JavaScript that implements an even-odd rule of negative signs in algebra. In a series of negative and positive signs:

  • Case 1 : if there is an odd number of negative signs, this is equivalent to a negative sign
  • Case 2 If there is an even number of negative signs, this is equivalent to a positive sign.

So, I would do .replace(/regex for case1/, "-") and .replace(/regex for case2/, "+") . Any idea on how to do this?

Here is an example line:

  • \frac{a^{n+-m}}{b} β†’ \frac{a^{nm}}{b}
  • abc+cde=ghj--+--hsnj β†’ abc+cde=ghj+hsnj
+6
source share
5 answers

Well, you can replace all + with -- , and then replace accordingly:

 expr.replace(/\+/g, '--').replace(/(--)+-/g, '-').replace(/--/g, '+') 

Or you can use the function in .replace to count the quantity - s:

 expr.replace(/[-+]+/g, function(signs){ return '+-'[signs.replace(/\+/g, '').length % 2]; }); 
+1
source

([^-+]|^)(?:[+]*-[+]*-)*[+]*-[+]*([^+-]) for an odd number of hyphens, as you can see https: / /regex101.com/r/fU0vY7/4 , must be replaced with $1-$2

([^-+]|^)(?:[+]*-[+]*-[+]*)+([^+-]) for an even number of hyphens, as can be seen https://regex101.com/ r / fU0vY7 / 5 , must be replaced with $1+$2

You can use both substitutions on the same line. So far, everything I tested has worked, including your examples. If something doesn’t work, tell me.

It would be more convenient to avoid capture groups, but the lack of lookbehind in javascript forced me to add capture groups and $1+-$2 respectivelly

+1
source

As vks points out, regular expressions cannot, strictly speaking, count. You can cancel pairs, as in Andris's answer , but as you can see, regular expressions get a little long when you cover all cases. An alternative is to combine a regular expression with a normal function:

 function do_replacement(x) { return x.replace(/[+-]+/g, function (r) { return r.replace(/\+/g, '').length % 2? '-' : '+'; } ); } 

This divides the task into two parts:

  • Use regex to match any sequence + and -
  • In the replace function, remove + from the matched string and count the remaining characters (which, thanks to the original regular expression, can only be - s)
  • Return either + or - , depending on whether the count is even (i.e. length % 2 is zero) or odd
+1
source
 function replace(str) { return str.replace(/[+-]+/g, function(matched, pos, full) { // + is 0, - is 1 // the counting is same as XOR of all +/- signs return matched.split('').reduce(function(a,b) { return a ^ (b == '-'); }, 0) ? '-' : '+'; }); } 
0
source
 Consider a number say x, get x%2 if x%2!=0, then '-', else '+' 

This is just an algorithm. Hope you can get your solution here.

-1
source

All Articles