How to make regular expression unique for multiple values

Viewed 849

My response having same values at 2 places like

http://images.123456_120*75
http://images.123456_120*75
http://images.784217_120*75
http://images.784217_120*75

In this I need to capture 123456 & 784217 only one time.

I was using regex as http://images.(.+?)_120*75 which extracting all 4 values .But my concern is I need one value among 2 for each. Can u pls help me thanks in advance ?

4 Answers

One way, is to have 2 post processor with the same regex. Now, in the 1st regular extractor use Match No: value as 1 and in 2nd use Match No: value as 4.

enter image description here

Hope this helps.

Doing it using regular expressions is quite tricky, I would recommend going for JSR223 PostProcessor and Groovy language instead.

  1. Add JSR223 PostProcessor as a child of the request which returns above images URLs
  2. Put the following code into "Script" area

    (prev.getResponseDataAsString() =~ "http://images.(\\d+)_120\\*75").findAll().unique().eachWithIndex {match, idx ->
        vars.put('image_' + idx,match.get(1))
    }
    
  3. If everything goes well you should see the following JMeter Variables generated:

    image_0=123456
    image_1=784217
    etc.
    

This should work, it captures unique values only once:

(\d+)(?:_)(?![\s\S]*\1)

Try Demo here

Explanation

(\d+)(?:_)(?![\s\S]*\1)

1st Capturing Group (\d+)

\d+ matches a digit (equal to [0-9])

  • Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)

Non-capturing group (?:_)

_ matches the character _ literally (case sensitive)

Negative Lookahead (?![\s\S]*\1)

Assert that the Regex below does not match Match a single character present in the list below [\s\S]*

  • Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)

\s matches any whitespace character (equal to [\r\n\t\f\v ])

\S matches any non-whitespace character (equal to [^\r\n\t\f\v ])

\1 matches the same text as most recently matched by the 1st capturing group

Perhaps you could capture the whole match in a group and capture the digits in a second group. Then use a negative lookahead to assert that what is captured in group 1 does not occur anymore giving you the unique values.

The digits you want to match are in capturing group 2. Note that to match the dot . and the asterix * literally you have to escape them.

(http://images\.(\d+)_120\*75)(?![\s\S]*\1)

Regex demo

Related