2

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.

4
  • what about --++? will there be any such value Commented May 6, 2016 at 7:41
  • I have no idea where you get these values, but if there's some "math-logic" shouldn't '--'='+'? Commented May 6, 2016 at 7:43
  • No.its just ah constant Commented May 6, 2016 at 7:45
  • 2
    '10++10--10+-10-+'.replace(/(\+\+)|([-+]-|-\+)/g, function(m,g1,g2){return g1?"+":"-";}); Commented May 6, 2016 at 7:48

2 Answers 2

1

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 -+.

Sign up to request clarification or add additional context in comments.

Comments

1

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
  )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.