0

I'm trying to build a regex match with variables as part of the matched string:

var_a := 'somestring'
var_b := 'someotherstring'

IF EXISTS (SELECT 1 FROM some_table WHERE some_field ~* 'var_a.+?(?=\-)\-var_b)')

How do I insert the variables into the string? Like in js you can simply do:

`${var_a} restofstring`

1 Answer 1

1

You could use the format() function:

WHERE some_field ~* format('%s.+?(?=\-)\-%s)', var_a, var_b)
Sign up to request clarification or add additional context in comments.

4 Comments

I've just managed to do the same thing (before reading your answer) like so: ~*(var_a||'.+?'||var_b) It seems to work. Is it also acceptable or should I use the format function with % for the vars?
@S.Schenk: I find solutions using format() way easier to read and maintain compared to the equivalent using ||. But that's largely personal taste. But it becomes "mandatory" if it's used to generate dynamic SQL.
It's mandatory when used for dynamic sql to prevent sql injections right?
That's one of the reasons, yes. I wrote "mandatory" in the sense that it's the only sane option where the base SQL is still readable.

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.