Replacing special characters with underscore in apex or trigger.I am using below things but getting error.
string groupname=(gr.name).replace(/[^A-Z0-9]+/ig, '_');
Error: expecting a right parentheses, found '/'
But working in javascript and java but not in apex trigger.
For testing i have used below code snippets
String abc = 'SVP, Customer Service & Support group';
string groupname=abc.replace('/[^A-Z0-9]+/ig', '_');
System.debug('value of string :::: '+groupname);
But it returned me below : SVP, Customer Service & Support group but i want to be returned like SVP_Customer_Service___Support_group
Best Answer
Java and JavaScript are completely unrelated to each other. Likewise, Apex Code is a descendant of Java, and is a complete stranger to JavaScript. Java requires patterns and such to be enclosed in a string, while JavaScript treats /.../ constructs as syntactic sugar for a more formal structure (this is closely related to how Perl performs its' regular expressions).
In Java, you set/unset flags using (?...). There is no
g
flag, but you can use thei
flag for case insensitivity. Also, I should mention thatreplace()
is a literal replacement, whilereplaceAll()
is used with a regular expression. So, your code should look more like:If you choose not to use the
i
flag, you could also have written: