Marek R
Marek R

Reputation: 38052

How to escape regular expression characters from variable in JMeter?

Problem is simple. I have regular expression used to extract some data from response. It looks like that:

<input type="hidden" +name="reportpreset_id" +value="(\w+)" *>${reportPresetName}</td>

Problem is that variable ${reportPresetName} may contain characters used by regular expression like parenthesis or dots.
I've tried to surround this variable with \Q and \E (based on that) but apparently these markers don't work (apparently Java supports this markers so I'm confused). When I'm adding that markers even then this expression fails for any content of ${reportPresetName} variable (even for cases when it was working without those markers).

I've checked list of functions in JMeter, but I didn't found anything useful. Does anyone know how to escape regular expression characters in JMeter?


update:
When I'm using this \Q and \E with assertion it fails. When I'm doing a copy of regular expression from assertion log in "View Results Tree" and testing it on recorded response data it works! So it looks like some kind bug in JMeter.

Upvotes: 1

Views: 15064

Answers (3)

UBIK LOAD PACK
UBIK LOAD PACK

Reputation: 34536

Jmeter uses jakarta ORO as its regexp engine in Regexp Extractor and Regexp Tester:

But it uses Java Regexp Engine for search in HTML/Text Viewer.

Read:

A solution for you would be to add a JSR223 post processor using Groovy after regexp that extracts the var and escapes regexp chars using:

org.apache.oro.text.regex.Perl5Compiler.quotemeta(String valueToEscape)

As of upcoming version 2.9, a new function has been created to do so:

  • __escapeOroRegexpChars(String to escape, Variable Name)

Upvotes: 3

Ωmega
Ωmega

Reputation: 43683

In case JMeter does not support \\Q and \\E (which I don't know if does...), you can write your own function/procedure, where you will split string into characters and replace each character with escaped sequence as follows:

  • if the character is \, then replace it with \\\\
  • otherwise add before the character a prefix \\

This is not the optimal method, but for sure it will work as needed.


For example for input

This is-a\string 12&$34|!`^5

you will get

\\T\\h\\i\\s\\ \\i\\s\\-\\a\\\\s\\t\\r\\i\\n\\g\\ \\1\\2\\&\\$\\3\\4\\|\\!\\`\\^\\5

Upvotes: 0

PhiLho
PhiLho

Reputation: 41152

\Q and \E work in Java, see Pattern.

In Java, we use to double the backslash characters, though, so you might need to use (\\w+) and, of course, \\Q and \\E.

I am not sure in your case, as I don't understand your context, actually (never used JMeter so far).

Upvotes: 1

Related Questions