Search code examples
regexplsqlregexp-replace

Regex matching numerical variable names


suppose that we have following string:

$6 
$7 

You have received the grade of $3 in the subject $1 ($10) in the semester $2 ($11). 
Grade date: $4 
Entered: $5 

I need to figure out how to dynamically and corrcetly replace those variables. And suppose we have folloving PL/SQL pseudo-code:

for i in 1..X loop
  l_str := regexp_replace(l_str, '\$'||to_char(i), l_replace(i));
end loop;

But when it comes to first iteration - $1, $10, $11 variables are being replaced - but only $1 is correct.

Does anyone have advice how to fix it?


Solution

  • Your regexp matches anything starting with $ and a current iteration number. If you need to replace all those variables with the same string, you don't need a cycle there as you can simply do it like that:

    l_str := regexp_replace(l_str, '\$[0-9]+','SOME_STRING');
    

    if you need to have different different replacements, you can do it similarly:

    for i in 1..X loop
      l_str := regexp_replace(l_str, '(\$'||to_char(i)||')([^0-9]+|$)',l_replace(i)||'\2');
    end loop;