Home > Software design >  A clean way to replace the last occurrence if bracketed number in a string [duplicate]
A clean way to replace the last occurrence if bracketed number in a string [duplicate]

Time:09-16

I want to create a simple and relatively performant function that takes a string and returns a transformed string such that the last occurence of [<any number of digits>] gets removed. Brackets not containing only digits should not be treated as any other string. For example:

transform('222') // 222
transform('222.[0].333') //222..333
transform('222.[0].[12312].333') // 222.[0]..333
transform('222.[0].[notDigits].333') // 222..[notDigits].333
transform('222.[0].[].333') // 222..[].333

What is a clean way of achieving this with good performance?

CodePudding user response:

Here's a regex solution. Matches the last bracket and removes it.

const transform = (str) => str.replace(/(\[\d \])(?!.*\[\d \])/gm, "");


const res1 = transform('222') // 222
const res2 = transform('222.[0].333') //222..333
const res3 = transform('222.[0].[12312].333') // 222.[0]..333
console.log(res1)
console.log(res2)
console.log(res3)

CodePudding user response:

This should be entirely possible using a RegExp (with a negative lookahead, I think?), however my regex-fu isn't strong enough - but doing it using normal RegExp methods should also work:

function removeLastSquareBracketedDigits( input/*: string*/ )/*: string*/ {
    
    const r = /(\[\d \])/g;
    const m = Array.from( input.matchAll( r ) );
    if( m && m.length > 0 ) {
        const lastMatch = m[ m.length - 1 ];
        const idx = lastMatch.index;
        const end = idx   lastMatch[1].length;
        return input.substring( 0, idx )   input.substring( end );
    }
    else {
        return input;
    }
}

Results:

removeLastSquareBracketedDigits('222')                 === '222'
removeLastSquareBracketedDigits('222.[0].333')         === '222..333'
removeLastSquareBracketedDigits('222.[0].[12312].333') === '222.[0]..333'

CodePudding user response:

use this regex that will remove last bracket

/(.*)\[([^\]] )\]([^\]]*)/

e,g

function transform(string){
    return string.replace(/(.*)\[([^\]] )\]([^\]]*)/,function(match,p1,p2,p3){return p1 p3})
}

Results:

transform('222') // 222
transform('222.[0].333') //222..333
transform('222.[0].[12312].333') // 222.[0]..333
  • Related