Home > Back-end >  regex replace last occurance of number in between 2 chars javascript
regex replace last occurance of number in between 2 chars javascript

Time:02-11

I am trying to replace the last number of each match in between parenthasees.

so if i had cos(3 * 3)

before this regex

result = result.replace(/\d (?:\.\d )?/g, x => `${x}deg`)

would turn cos(3 * 3) into cos(3deg * 3deg) I need only the last number to be changed to deg so if I had cos(3 * 3) cos(3 * 2) it would be cos(3 * 3deg) cos(3 * 2deg)

what regular expression magic could I use to do this.

CodePudding user response:

You can simply use the closing braces to replace like this:

var result = "cos(3 * 3)   cos(3 * 245)"

result = result.replace(/(\d )(\))/g,'$1deg)')

console.log(result)

Or just replace the last bracket.

var result = "cos(3 * 90)   sin(3 * 2)"

result = result.replace(/\)/g,'deg)')

console.log(result)

With Decimal add a character class using [] for . and digits

var result = "cos(3 * 3.4)   cos(3 * 245.5)"

result = result.replace(/([\d\.] )(\))/g,'$1deg)')

console.log(result)

Any equation at the last number

var result = "3*(1571-sin(12))"

result = result.replace(/(\d\s{0,}\* \d{0,})(.*\))/g,'$1$2deg')

console.log(result)

CodePudding user response:

... /\((?<first>.*?)(?<last>[\d.] )\)/g ...

// see ... [https://regex101.com/r/aDXe3B/1]
const regXLastNumberWithinParentheses =
  /\((?<first>.*?)(?<last>[\d.] )\)/g;

const sampleData =
`cos(3 * 3)   cos(3 * 24.5), cos(2 * 3)   cos(3 * 2.4)
cos(3 * 3.4)   cos(3 * 45), cos(4 * 2)   cos(3 * 245)`;

console.log(
  sampleData.replace(
    regXLastNumberWithinParantheses,
    (match, first, last) => `(${ first }${ last }deg)`
  )
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

  • Related