Write an invocable apex class to remove characters from a string

apexinvocable-methodreplaceallstring

Fairly new to Apex so please bear with.

I am trying to write a simple Apex Class that makes use of the replaceAll function to remove unnecessary characters from a string.

I've got as far as the following:

    public class ReplaceApex {
    @InvocableMethod(label = 'Regex Replace' description = 'Get rid of unwanted characters' category = 'User')
  public static List<String> regexReplace(List<RegexReplace> regexReplace) {
    RegexReplace r = regexReplace[0];
    String regexResponse = r.replaceAll('[^A-z0-9?-]','');
    List<String> ret = new List<String> {regexResponse};
    return ret;       
    }
    public class RegexReplace {
    @InvocableVariable(required = true)
    public String question;
  }
}

But I am getting the error:

Method does not exist or incorrect signature: void replaceAll(String, String) from the type ReplaceApex.RegexReplace

How do I get around this problem?

Thanks in advance!

Best Answer

replaceAll method is available for string class

https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_methods_system_string.htm

You are trying to use this method on RegexReplace class which does not exist. hence facing this error.

Solution

  1. Mostly it seems like you want to remove characters from question
    based on regex. So replace

String regexResponse = r.replaceAll('[^A-z0-9?-]','');

with

String regexResponse = r.question.replaceAll('[^A-z0-9?-]','');

  1. Or you can implement replaceAll method in RegexReplace class
Related Topic