2

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

3
  • the regex expression to replace(..) has to be an apex string
    – cropredy
    Oct 2, 2015 at 19:51
  • can you change it to apex string.Do you mean /[^A-Z0-9]+/ig has to be inside quotes like '/[^A-Z0-9]+/ig'
    – Jack vardy
    Oct 2, 2015 at 19:55
  • 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
    – Jack vardy
    Oct 2, 2015 at 19:57

1 Answer 1

4

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]
1
  • Thank You! sfdcfox I was trying since 2 And half hour.Finally i got the solution.
    – Jack vardy
    Oct 2, 2015 at 20:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.