user34829
user34829

Reputation: 1325

Reduce multiple whitespaces to a single space in KDB+/Q

To get from "a b" to "a b"

ssr["a         b";"[ ]+";" "]

doesn't seem to work. Thanks!

Upvotes: 1

Views: 776

Answers (2)

Connor Gervin
Connor Gervin

Reputation: 946

You can use the following which treats each repeating space as a pair, then using over, 'replaces' these with a single space.

q)x:"This         is    a    test"

q)(" "sv"  "vs)/[x]

"This is a test"

Upvotes: 2

Thomas Smyth
Thomas Smyth

Reputation: 5644

It is possible to do this more efficiently then using vs and sv. Using the adverb each-prior ':

{x where not(and':)null x}"This         is    a    test"
"This is a test"

Alternative you can using ssr with the adverb over / in order to continuously remove blocks of two spaces:

ssr[;"  ";" "]/["This         is    a    test"]
"This is a test"

The example you provided fails due to the limited regex options available, using + in this sequence "[ ]+" is an example of an operation that is not supported. You can read more about regex in q on the kx wiki.

Upvotes: 0

Related Questions