How can I write all values extracted via regex to a file?

廉价感情. 提交于 2021-01-29 08:08:20

问题


I've got a piece of regex which I've tested in JMeter using the regexp tester and it returns multiple results (10), which is what I'm expecting.

I'm using the Regular Expression Extractor to retrieve the values and I would like to write ALL of them to a CSV file. I'm using the Beanshell Post Processor but I am only aware of a method to write 1 value to file.

My script in Beanshell so far:

temp = vars.get("VALUES"); // VALUES is the Reference Name in regex extractor

FileWriter fstream = new FileWriter("c:\\downloads\\results.txt",true);
BufferedWriter out = new BufferedWriter(fstream);
out.write(temp);
out.close();

How can I write all the values found via the regex to file? Thanks.


回答1:


If you'll look into Debug Sampler output, you'll see that VALUES will be a prefix.

Like

  • VALUES=...
  • VALUES_g=...
  • VALUES_g0=...
  • VALUES_g1=...

etc.

You can use ForEach Controller to iterate over them.

If you want to proceed with Beanshell - you'll need to iterate through all variables like:

    import java.io.FileOutputStream;
    import java.util.Map;
    import java.util.Set;

    FileOutputStream out = new FileOutputStream("c:\\downloads\\results.txt", true);
    String newline = System.getProperty("line.separator");
    Set variables = vars.entrySet();

    for (Map.Entry entry : variables) {
        if (entry.getKey().startsWith("VALUES")) {
            out.write(entry.getValue().toString().getBytes("UTF-8"));
            out.write(newline.getBytes("UTF-8"));
            out.flush();
        }
    }

    out.close();



回答2:


To write the contents of your values array into the file, the following code should work (untested):

String[] values = vars.get("VALUES");

FileWriter fstream = new FileWriter("c:\\downloads\\results.txt", true);
BufferedWriter out = new BufferedWriter(fstream);

for(int i = 0; i < values.length; i++)
{
   out.write(values[i]);
   out.newLine();
   out.flush();
}
out.close();


来源:https://stackoverflow.com/questions/22364953/how-can-i-write-all-values-extracted-via-regex-to-a-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!