Search code examples
javaregextalend

Check if value has no digits, if so replace with 'Invalid' with shorthand Java


If a string has no digits in it, I would like to replace it with "Invalid" using Java (shorthand); this is to be an expression in the tMap component in Talend Open Studio

Here are some examples of desired outcomes:

Here are valid entries that should stay the same and remain unchanged, they are valid:

  1. "1234"

  2. "123-456-7890"

  3. "(123) 456-7890"

Here are some values that are to replaced with "Invalid":

  1. "asdf"

  2. "(xxx) xxx-xxxx"

  3. "() -() -()"

  4. "***-***-****"

  5. "- -"

Here's what I've tried so far:

myTable.myField.replaceAll("[0-9]","").isEmpty() ? "Invalid" : myTable.myField

But it's not working out, at least not in Talend


Solution

  • Just replace any string that's all digits, like this:

    myString.replaceAll("^[0-9]+$", "invalid");
    

    According to comments, OP wants to replace any strings that don't have digits in them. here's the answer for that:

    myString.replaceAll("^[^0-9]+$", "invalid");
    

    Also, this will replace strings that do have some digits:

    myString.replaceAll("^.*[0-9].*$", "invalid");