Is it possible to replaceall on a string using wildcards? For example

string adder;
adder = '[Test | 123 ! xyz]';
string replaced;
replaced = adder.replaceall('|%!','');

System.AssertEquals(replaced,'Test xyz');

Here I am using % as wildcard but it is not working.

1 Answer 1


The documentation for the replaceAll() method says that it accepts a Regular Expression as the first argument. If you wanted to get rid of everything between | and ! inclusive you can use adder.replaceAll('(\\|.*!)','');.

  • What I want to do is something like this: [Term: 1 | Vol: 1| Result:1][Term:2|Vol:2|Result:2] and if i want to grab all the terms do ReplaceAll('| Vol: % ]',']') so the result is [Term:1][Term:2] Jun 23, 2017 at 18:37
  • @AverageJoeVBA As stated in the answer (implicitly), you need to "escape" |, which normally means "OR", and you also need to escape the "\" that you use to escape the |, because that has special meaning in Apex Code (also an escape), so you have to write \\| to match a literal | character.
    – sfdcfox
    Jun 23, 2017 at 18:43
  • Awesome Jeff thanks for the updated answer. Worked to perfection, saved me some rework of splitting out the build of a string throughout a controller. Jun 23, 2017 at 18:44
  • I edited my comment once I re-read the question. The link I posted for Regular Expressions is a good place to get started, but each regex is going to be unique to the situation. In the example you just gave you would use replaceAll('(\\s?\\|[^\\]]*)','') Jun 23, 2017 at 18:45
  • Haha @AverageJoeVBA sorry I got distracted trying to build a new RegEx for you. Glad I could help. Leaving the new RegEx up though in case anyone else wants it. Jun 23, 2017 at 18:46

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .