I was trying to find an elegant solution to the following problem. I have the following string :
This ) is ) some $ text. ) lkzejflez $ aaeea ) aeee
Existing out of a part that is human readable text before the bold marked bracket and a part that just plain rubbish after the bracket. I need to find the human readable text in string alike this one. I need to get the text before the last bracket (bold marked) that still has a dollar sign (bold marked) behind it. Here is my solution to the problem :
const info = "This)is)$a sentence.)lkzejflez$aaeea)aeee";
let result;
for(let i = 0; i < info.length;i ){
const char = info[i];
const after = info.substring(i 1,info.length);
const otherChance = after.indexOf(')') < after.lastIndexOf('$');
if(otherChance){continue;};
const isEndBracket = char ===')';
const before = info.substring(0,i)
if(isEndBracket){result = before;break;};
}
console.log(result)
The expected result is 'This)is)$a sentence.' My code does return this result but it uses substr and a forloop where regex could be used. I do however not now how. Does anyone know a more elegant solution to my problem. Thanks in advance.
CodePudding user response:
Try the following regex: ^.*\)(?=.*\$)
Explanation: Match as many characters as possible from the start of the line to the last ) that is followed by a $.
Detailed explanation: Greedily match zero or more of any character except a newline from the start of the line to a ) character that is followed by zero or more of any character except a newline and then a $ sign.