prasanth
prasanth

Reputation: 22500

how to replace multiple value in single regex?

I have some values like 10++10--10+-10-+.my question is how to replace these value into matched value using single reg expression.i need a answer like 10+10-10-10-. its means

'++'='+',
'--'='-',
'+-'='-',
'-+'='-';

.please help me for solve my problem.

Upvotes: 2

Views: 735

Answers (2)

Mikaël Mayer
Mikaël Mayer

Reputation: 10711

A solution that is Regex only without callback function, so that it can be applicable in other languages that do not have regex replacement callbacks.

var s = '10++10--10+-10-+';
document.body.innerHTML = (s + "||||++=>+,+-=>-,-+=>-,--=>-" // Append replacements
  ).replace(/(\+\+|--|-\+|\+-)(?=[\s\S]*\1=>([^,]*))|\|\|\|\|[\s\S]*$/g, "$2" 
// Perform replacements and remove replacements
  )

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627419

Match and capture the alternatives you need to replace with a specific string, and then use the replace callback to see which group matched and replace accordingly:

var s = '10++10--10+-10-+';
document.body.innerHTML = s.replace(/(\+\+)|([-+]-|-\+)/g, function(m, g1, g2) { 
  return g1? "+" : "-";
});

The (\+\+)|([-+]-|-\+) regex contains 2 alternative groups since there are 2 replacement patterns. Group 1 (\+\+) will match double pluses while Group 2 - ([-+]-|-\+) - matches and captures --, +- and -+.

Upvotes: 1

Related Questions