我想替换字符串中的一些单词,我知道我可以使用gsub
方法。但我的情况是假设我有一个以下字符串:
"(_query_:"{!edismax qf='judgment_order_text^3.0 parallel_citation_text^3.5 judgment_order_exact^3.0 in_favor_of_exact^3.5 parallel_citation_exact^3.5 judge_names_exact^3.5 headnote_exact^3.3 headline_exact^3.3 court_level_exact^3.5 section_index_exact^3.5 appellant_exact^3.5 respondent_exact^3.5 year_exact^3.5 assessment_years_exact^3.5 AND _query_:"{!edismax qf='in_favor_of_text^1.3 in_favor_of_ngram^0.8 in_favor_of_exact^3.5' mm='1' pf='in_favor_of_text^1.0 in_favor_of_ngram^1.0 in_favor_of_exact^5.0'}revenue")"
现在我要替换exact
和(_query_:
之间发生的AND _query_:
字词。如何使用ruby做到这一点?
我期待以下输出:
"(_query_:"{!edismax qf='judgment_order_text^3.0 parallel_citation_text^3.5 AND _query_:"{!edismax qf='in_favor_of_text^1.3 in_favor_of_ngram^0.8 in_favor_of_exact^3.5' mm='1' pf='in_favor_of_text^1.0 in_favor_of_ngram^1.0 in_favor_of_exact^5.0'}revenue")"
答案 0 :(得分:0)
您可以使用String#sub
或String#gsub
轻松完成此操作。这里:
a = "\"(_query_:\"{!edismax qf='judgment_order_text^3.0 parallel_citation_text^3.5 judgment_order_exact^3.0 in_favor_of_exact^3.5 parallel_citation_exact^3.5 judge_names_exact^3.5 headnote_exact^3.3 headline_exact^3.3 court_level_exact^3.5 section_index_exact^3.5 appellant_exact^3.5 respondent_exact^3.5 year_exact^3.5 assessment_years_exact^3.5 AND _query_:\"{!edismax qf='in_favor_of_text^1.3 in_favor_of_ngram^0.8 in_favor_of_exact^3.5' mm='1' pf='in_favor_of_text^1.0 in_favor_of_ngram^1.0 in_favor_of_exact^5.0'}revenue\")\"\n"
replacement = "\"{!edismax qf='judgment_order_text^3.0 parallel_citation_text^3.5"
puts a.sub(a[/_query_:(.*) AND _query_/, 1], replacement)
# "(_query_:"{!edismax qf='judgment_order_text^3.0 parallel_citation_text^3.5 AND _query_:"{!edismax qf='in_favor_of_text^1.3 in_favor_of_ngram^0.8 in_favor_of_exact^3.5' mm='1' pf='in_favor_of_text^1.0 in_favor_of_ngram^1.0 in_favor_of_exact^5.0'}revenue")"