[SalesForce] Replacing special characters with underscore doesn’t work in apex. Works in Javascript

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 the i flag for case insensitivity. Also, I should mention that replace() is a literal replacement, while replaceAll() is used with a regular expression. So, your code should look more like:

String groupName = gr.name.replaceAll('(?i)[^a-z0-9]', '_');

If you choose not to use the i flag, you could also have written:

[^a-zA-Z0-9]
Related Topic