在SystemVerilog中搜索和替换字符串

时间:2015-01-15 18:10:15

标签: string replace system-verilog

在SystemVerilog中进行字符串搜索和替换的最简单方法是什么?

例如,我有:

string hdl_path = "DUT.my_red39";

如何创建一个用蓝色替换红色的新string

EDA Playground link

1 个答案:

答案 0 :(得分:2)

您可以使用最近创建的SystemVerilog实用程序库之一。

ClueLib

svlib

或者,您可以通过比较单个字符来使用普通的SystemVerilog:

  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