简体   繁体   English

对于 ruby 中的给定场景,如何使用 gsub?

[英]How to use gsub for the given the scenario in ruby?

I am giving the values as:我给出的值是:

str = 'test["test1", "test2"]'

Using gsub , I want the value as '["test1", "test2"]' .使用gsub ,我希望值为'["test1", "test2"]'

The condition is, the values before and after braces [ / ] should be removed.条件是,大括号[ / ]前后的值应该被删除。

This should remove anything before and after [ and ] :这应该删除[]之前和之后的任何内容:

str.gsub(/^[^\[]+/, '').gsub(/[^\]]+$/, '')

By parts:按零件:

> str = 'test["test`", "test2"]test'
 => "test[\"test`\", \"test2\"]test" 
> str.gsub(/^[^\[]+/, '')
 => "[\"test`\", \"test2\"]test" 
> str.gsub(/[^\]]+$/, '')
 => "test[\"test`\", \"test2\"]" 
> str.gsub(/^[^\[]+/, '').gsub(/[^\]]+$/, '')
 => "[\"test`\", \"test2\"]" 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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