Regex strip trailing zeros in a comma separated string

Hello,

I have the following string …
0,0,4,1,0,3,5,7,0,0,0

With my current regex I can strip the initial two zeros. What I would like to achieve, is to strip out the final three zeros as well, but keeping the middle position zero, you probably know already :wink:

^[0,]+(.*)[,0]+$

image

Expected:
4,1,0,3,5,7

no hurries
BR

Hello gonhaddock,

what about repeating the formula two times? Strip the initial zeros with your formula, then sort your list in decreasing order and reapply the regex.

RB

Hello @gonhaddock,

make it non-greedy with ? in capturing group. (See here for more.)

^[0,]+(.*?)[,0]+$

(I used above expression in Regex Split node.)

Br,
Ivan

Hi @lelloba
I was looking the most efficient one step code. Two steps is a solution, but I will give a chance for it.

Thanks

image

Genial:
image

Thanks a lot


  1. 0, ↩︎

Hey Guys,

this looks awfully similar to this weeks Just KNIME It! Challenge! :laughing:
Especially if you take a look at this solution:

@gonhaddock maybe you want to post it there? :wink:

@lelloba , I’m sure that was just an example from @gonhaddock . What if there’s a case of 5 zeros at the end? Or a variety of them (as in unknown number of zeros at the end)?

Hello Bruno,

sorry but I am not sure I have understood your question.
Gonhaddock said his code could strip the first zeroes but not the last ones. The solution I proposed (I am not a regex expert) was to apply the code with the right sequence (first to last), then resort it in decreasing order (last to first) to reapply the regex again.
Not the best solution, but it should work. It should work independently on the number of 0s at the beginning or end, shouldn’t it?

RB

Hi @lelloba , sorry I think I misunderstood what you meant, but it makes sense now.

I thought you meant re-applying the same regex because of the amount of zeros at the end, therefore I thought that it was not a generic solution. But what you said would work.

Sorry about the misunderstanding on my part and about the confusion.

Hi,
For those using literal @ipazin 's solution, the space can be also removed with the following update:
^[0, ]+(.*?)[, 0]+$

No extra nodes needed for removing the spaces :wink:

BR