1

I want to create variable: Number which extract numbers before $

Name      | Number
abc1/12 $ | 12
12av 12$  | 12
114$-bgv  | 114

I have a query:

select Name, substring(Name FROM '%#"[0-9]+#"$%' FOR '#') as Number
from table;

But it returns:

Name      | Number
abc1/12 $ | 
12av 12$  | 2
114$-bgv  | 4

Any ideas?

5
  • substring(Name from '(\d+)\$') Commented May 23, 2016 at 13:05
  • i updated the problem - please check again. Commented May 23, 2016 at 14:45
  • It's simple: '(\d+)\s*\$' Commented May 23, 2016 at 15:04
  • it does not work. and additionaly if I want to extract from pattern 'number+'gb' (i.e. 15gb) instead of number+$ (i.e. 15$) it returns 'invalid escape \ sequence'; using postgresql 9.2 Commented May 23, 2016 at 15:36
  • "It does not work" is a bad description of the problem. And be more specific about what exactly you want to extract. Additionally it seems that you unfamiliar with regular expressions (I am unfamiliar too :) Learn more about its syntax. In short: dollar sign '$' should be escaped by slash because it means EOL in regular expressions. However gb is a simple substring so it is not needed to be escaped: '(\d+)\s*gb. Thats why you getting 'invalid escape sequence' error. Good luck. Commented May 23, 2016 at 16:11

1 Answer 1

1

Use regexp_matches():

select
  (regexp_matches(Name,  '^(.*[^\d]+){0,1}(\d+)\$'))[2] as Number
from (
  select 'abc1/12$' as Name
  union select '12av 12$'
  union select 'bgv-114$'
  union select '124$'
) t

Or with substring()

select
  coalesce(substring(Name FROM '.*[^\d]+(\d+)\$'), '') ||
  coalesce(substring(Name FROM '^(\d+)\$'), '') as Number
from (
  select 'abc1/12$' as Name
  union select '12av 12$'
  union select 'bgv-114$'
  union select '124$'
) t
Sign up to request clarification or add additional context in comments.

2 Comments

This does not handle '5$ foo'
More transparent query is with using regexp_matches().

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.