Java Snippet to Replace All Values in a Column

Hi all,

I would say I'm a beginner around KNIME´s environment, and my background in Java programming is almost zero. I would like to see if someone could help me with a (simple) code for replacing all values in a column following a specific pattern. I have tried basic nodes offered by KNIME but I don't believe they are suitable for the work I want to perform. Hereby, an example of what I want to do.

Given this column:

Event

Hi Peter
Peter is nice

John looks great

Peter is tall

John is blind

 

I would like to replace the column cells (strings) in such a way: wherever there is Peter written, replace by Peter, and the same with John. Final result would look like:

Event

Peter

Peter

John

Peter

John

 

Thank you in advance! Hope you can help me somehow:)

 

Pablo

 

int columna=$events$;
String[] names = {"Peter","John"};
 
for(i=0;i<matrix.length;i++){
   if(matrx(i,columna).toLowerCase().contains(names(0).toLowerCase())){
      matrix(i,columna)="Peter";
   }
   if(matrx(i,columna).toLowerCase().contains(names(1).toLowerCase())){
      matrix(i,columna)="John";
   }
}
 
I think this could be a possible Code, but I don`t know how to translate it into KNIME...
 
Can anyone help me?
 
Thanks,
 
Pablo

Hi Pablo,

put this in "Global Variable Declaration":

static final String[] STRINGS = {"peter","john"};

… and this in "Method Body":

for (String s : STRINGS) {
    if ($text$.toLowerCase().contains(s.toLowerCase())) {
        return s;
    } 

}
return null;

Regards, Philipp

Hey Philipp,

Nice, it worked perfectly!

Best regards,

Pablo

Hi, just to let you know you could have done this with two consecutive string replacer nodes also, alleviating the need for any programming.
In the node, you would specify the wild card pattern as John and choose the replacement text as John. Choose the option of Replace whole string.
You would then repeat this in the next string replacer node with Peter.
Simon.

Hi Simon,

I had already tried the option you mention, but it doesn´t work. Even though selecting "replacing whole string", it only changes the word specified as "wildcard" pattern and not the whole cell value. For instance, if I want to change all Peter for Peter Williams in the example I previously wrote, it would write:

Hi Peter Williams (that is, changing Peter for Peter Williams but leaving the remaining content)

Best,

Pablo

That is strange, I have just tried it out using your example and it works perfectly, giving the outcome below;

Event

Peter Williams

Peter Williams

John looks great

Peter Williams

John is blind

 

All I am choosing is *Peter* as wildcard pattern, Peter Williams as replacement text, and "Replace Whole String" dotted. Is your KNIME up to date at 2.5.4?

Simon.

Ok, I was just missing both * so that´s why it didn´t work.

Thanks!!

Pablo