Extracting a number from a string in system verilog

Hi all,

Let’s say I have the following string:

string my_str = "Packet #3 size is 1500B";

I would like to extract the packet size (here 1500) and to assign it to an int. What will be the more efficient way to achieve that?

Thanks,
Ruben

In reply to rubendah:


module testbench();
  string my_str = "Packet #3 size is 1500B";
  int cnt, pkt_size;
  
  initial begin
    if ($sscanf(my_str, "Packet #3 size is %0dB", pkt_size) == 1)
      $display("Packet size is %0d", pkt_size);
    else
      $display("Unable to parse packet size from string");
  end
endmodule

Thanks for your answer.

I think my example was too simple. In my case, I do not know the exact string but I’m sure that the pattern “packet size is XB” will be present.

In reply to rubendah:

It is best to use a regular expression for this. See System veilog Regular expressions | Verification Academy

Otherwise you can the following steps

  1. Convert the string to an array of bytes
  2. Remove any trailing spaces
  3. Use find_last_index on the array to find the last embedded space.
  4. Use substr() to select the last word in the orginal string.
  5. Use $sscanf to convert that last word to a value.

In reply to dave_59:

Hi Dave,

A follow up question on this if I may -
I have a match using uvm_re_match (returning 0 - to my understanding it means the string matches)
How do I extract the actual searched sub-strings after the match? I can’t find any method that does that.

Thanks!

In reply to DLIS:

You cannot use uvm_re_match directly, but you could take the code and modify it to suit your needs.

However, many tools have already extended SystemVerilog by adding str.match() and str.backref() methods to extract substrings. Check your tools user manual. There is also an svlib package from Verilab.