KB Article #177478

Capturing part of the matched regex in a String Replace filter

Problem

When using the String Replace filter, how do you capture part of the match for use in the replacement?

Resolution

You need to reference one or more of the regex capture groups in the replacement string. The item matched within the first set of parentheses is called $1, the second is called $2, etc., just as when doing replacements with a java.util.Pattern. For example, the following filter configuration would change value of the parameter test.path from /one/two/three into just /one




This works because the regex matches any string starting with a forward slash and captures the forward slash followed by any number of non-forward slash characters into the first capture group. The entire string is then replaced with the value of the first capture group. So the entire string /one/two/three gets matched, $1 contains the string /one and then matched part, which was the entire string, gets replaced with the capture, setting the final value of test.path to /one