0

Consider a string like Ana (16) and Brian (14) are my children.

How to get the value of the first parenthesis? ('16' in this case.)

I tried with substring('Ana (16) and Brian (14) are my children.' from '\((.+)\)')

But it gives wrong result as 16) and Brian (14. (I can get it through strpos and substring combination. But need a better solution with regexp.)

2
  • It's important when asking for help that instead of saying "it gives wrong results" that you actually include the wrong results. That's a key part of debugging, to see the wrong results. It gives important clues as to what is wrong. Commented Jul 2, 2024 at 17:48
  • Hi @AndyLester, yes. It is given in the question now. Commented Jul 2, 2024 at 17:54

2 Answers 2

2

Your regex is almost correct, you just need to use non-greedy repetition to match the shortest string: +? instead of just +:

# select substring('Ana (16) and Brian (14) are my children.' from '\((.+?)\)');
 substring
-----------
 16
(1 row)
Sign up to request clarification or add additional context in comments.

Comments

1

I like to use the regex functions, like regexp_matches. This one works:

SELECT (regexp_matches('Ana (16) and Brian (14) are my children.', '\(([^)]+)\)'))[1];

Comments

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.