简体   繁体   中英

String search and replace in SystemVerilog

What's the easiest way to do string search and replace in SystemVerilog?

For example, I have:

string hdl_path = "DUT.my_red39";

How do I create a new string that replaces red with blue ?

EDA Playground link

You can use one of the SystemVerilog utility libraries that have been created recently.

ClueLib

svlib

Alternatively, you could do it with plain SystemVerilog by comparing individual characters:

  function automatic string search_replace(string original, string old, string replacement);
    // First find the index of the old string
    int start_index = 0;
    int original_index = 0;
    int replace_index = 0;
    bit found = 0;

    while(1) begin
      if (original[original_index] == old[replace_index]) begin
        if (replace_index == 0) begin
          start_index = original_index;
        end
        replace_index++;
        original_index++;
        if (replace_index == old.len()) begin
          found = 1;
          break;
        end
      end else if (replace_index != 0) begin
        replace_index = 0;
        original_index = start_index + 1;
      end else begin
        original_index++;
      end
      if (original_index == original.len()) begin
        // Not found
        break;
      end
    end

    if (!found) return original;

    return {
      original.substr(0, start_index-1),
      replacement,
      original.substr(start_index+old.len(), original.len()-1)
    };

  endfunction

SystemVerilog replace example on EDA Playground

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM