简体   繁体   中英

Replace a words which occurs in between the two words + ruby

I want to replace some words in a string, and I know I can use a gsub method. But my scenario is suppose I have a following string:

"(_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")"

now I want to replace exact word which is occurring in between the (_query_: and AND _query_: . How to do that by using a ruby ?

I am expecting following output:

"(_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")"

You can easily do this using String#sub or String#gsub . Here:

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")"

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