extract number from string in kdb

2019-08-09 08:40发布

问题:

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

回答1:

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


回答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


回答3:

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.



标签: kdb q-lang