Question

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

Was it helpful?

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");

OTHER TIPS

you have to set it so something:

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

However in this case I would use an if statement:

if (myTable.myField.replaceAll("[0-9]","").length() == 0){
    myTable.myField = new String("Invalid");
}

Why don't you use a very simple Pattern for that?

For instance:

String foo = "abc123";
String bar = "abcdef";
Pattern p = Pattern.compile("\\d");
System.out.println(p.matcher(foo).find());
System.out.println(p.matcher(bar).find());

Output:

true
false

So in your case:

if (p.matcher(myTable.myField).find()) {
    // I'm just making the method "setText" up - replace with actual method
    myTable.myField.setText("Invalid");
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top