Unlock a world of possibilities! Login now and discover the exclusive benefits awaiting you.
Hello,
I have to replace with 0 if my data contains at least one letter. Here is an example and what I tried. But I don't have the expected result.
It doesn't matter which letter, my column should only contain numbers. My column is of type string. The first condition works, but it is after the OR.
Thanks.
Sorry, I was a bit of an idiot there. I omitted to think about multiple scenarios 😬
A better way of doing this is to use this....
if(rep_numfac==null || rep_numfac.trim().equals("") || !rep_numfac.matches("[0-9]+")){
rep_numfac="0";
}
Essentially the above is saying, "If the rep_numfac is null OR rep_numfac is an empty String OR rep_numfac does NOT match just numbers".
Keep in mind, if you want to keep spaces or other symbols that are not numbers, you will need to modify the regex.
Something like this will work.....
if(rep_numfac.trim().equals("") || rep_numfac.split("[a-zA-z]+").length>1){
rep_numfac="0";
}
First of all, you don't need the "replaceAll" to test the result of all spaces removed. You can use "trim" for this. The second part is a bit of a trick. Not all of Java's String methods for finding values use regex. "Contains" doesn't use a regex. It tries to find the exact String. The "split" method does use a regex though. This method splits the String when it matches the regex and creates an array. So, if the array size is greater than 1, you know it has non-numeric characters.
Sorry, I was a bit of an idiot there. I omitted to think about multiple scenarios 😬
A better way of doing this is to use this....
if(rep_numfac==null || rep_numfac.trim().equals("") || !rep_numfac.matches("[0-9]+")){
rep_numfac="0";
}
Essentially the above is saying, "If the rep_numfac is null OR rep_numfac is an empty String OR rep_numfac does NOT match just numbers".
Keep in mind, if you want to keep spaces or other symbols that are not numbers, you will need to modify the regex.
Thank you very much for these detailed solutions, the explanation is very interesting and I have learned new things thanks to you! I'll make a note of this for another occasion😀