簡體   English   中英

gsub regex轉換成字符串

[英]gsub regex into a string

鑒於像一個字符串"this is the {{any}} string" ,我想gsub (或類似) {{any}}/.*/ ,然后使用整個字符串作為我的匹配。

您已經猜到,我已經嘗試過"this is the {{any}} string".gsub("{{any}}", /.*/) ,它給出了錯誤:

TypeError:沒有將Regexp隱式轉換為String

嘗試這個

string = "this is the {{any}} string"
regexp = Regexp.new(Regexp.quote(string).gsub("\\{\\{any\\}\\}", '.*'))

這是如何運作的?

  • Regexp.quote對字符串進行轉義,使其與逐字匹配
  • gsub{{any}}替換為.*
  • Regexp.new創建一個正則表達式

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM