3

I am quite new to kdb+q. I've come across this problem of extracting a number out of string.

Any suggestions?

Example:

"AZXER_1234_MARKET" should output 1234 //Assume that there is only one number in the 

string

chrisaycock
  • 36,470
  • 14
  • 88
  • 125
pikachuchameleon
  • 665
  • 3
  • 10
  • 27

3 Answers3

6

Extract the numbers then cast to required type.

q){"I"$x inter .Q.n} "AZXER_1234_MARKET"
1234i

q){"I"$x inter .Q.n} "AZXER_123411_MARKET"
123411i
q){"I"$x inter .Q.n} "AZXER_1234_56_MARKET"
123456i
q){"I"$x inter .Q.n} "AR_34_56_MAT"
3456i
John at TimeStored
  • 1,305
  • 7
  • 9
  • Nice answer. But I would suggest an alternate for this which is basically the same thing: {"I"$x inter "0123456789"} "AZXER_1234_MARKET" .Q.n is nothing but "0123456789" but .Q implementation is subjected to change as mentioned in q.k file(\d .Q /DO NOT USE ROUTINES PAST HERE. SUBJECT TO CHANGE). So it is not generally suggested to use it unless you are using any complex feature of it. – Rahul Jun 17 '14 at 16:17
2

If you have multiple numbers, here is a variation of the above, which allows for multiple numbers in one string

q)nums:{"I"$((where n&differ  n:x in .Q.n) cut x) inter\: .Q.n}
q)nums "this is 123 and this is 56"
123 56i
JPC
  • 1,891
  • 13
  • 29
1

I can suggest the following if we assume only one number in the string:

q)"AZXER_1234_MARKET"inter .Q.n
"1234"
q)"A_5643_B"inter .Q.n
"5643"

Then of course you can cast it to any type you want.

WooiKent Lee
  • 1,301
  • 6
  • 4