Ruby 字符串转义,用于序列化(字符串转储和加载)
我有一个字符串,我想对其进行序列化和反序列化。例如:
"hello, world"
现在,如果我用 o
查找并替换(dump 步骤)每个 world
子字符串,则该字符串将变为:
"hello, o"
但是,如果我尝试以其他方式从 o
到 world
(load 步骤)再次查找和替换,该字符串就会变成:
"hellworld, world"
...这与第一个字符串不同。有没有一种简单的方法可以用 Ruby 1.9.2 来处理这个问题,即转义字符?
谢谢你!
编辑:
换句话说,我将能够:
- 用值(例如“
o”)替换文本中的参数(例如“
”)。world
”) - 将任何值(“
o
”,根据示例)替换为参数(“world
”,根据示例)
所以我希望能够这样做(使用诸如 dump()
和 load()
方法):
string = "Hello world, Ruby on Rails 3.1.0 is out! Yay!"
serialized_string = dump(string)
# => "Hell\o o, Ruby \on Rails 3.1.0 is \out! Yay!"
load(serialized_string).should == string # => true
感谢您的任何想法:)
I have a string which I would like to serialize and deserialize. This one for instance:
"hello, world"
Now, if I find-and-replace (dump step) every world
sub-string by o
, this string become:
"hello, o"
But, if I try to find-and-replace again in the other way from o
to world
(load step), this string become:
"hellworld, world"
...which is not the same as the first string. Is there a easy way to handle this, escaping chars, with Ruby 1.9.2?
Thank you!
EDIT:
In other words, I would be able to:
- Replace a parameter (for example "
world
") in a text by a value (for example "o
"). - Replace any values ("
o
", according to the example) by the parameter ("world
", according to the example)
So I would like to be able to do so (with something like dump()
and load()
methods):
string = "Hello world, Ruby on Rails 3.1.0 is out! Yay!"
serialized_string = dump(string)
# => "Hell\o o, Ruby \on Rails 3.1.0 is \out! Yay!"
load(serialized_string).should == string # => true
Thanks for any idea :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
出于好奇,你为什么要这样做?
这与 ruby 没有太大关系,而是与正则表达式有关。
不管怎样,存储原始字符串以便恢复它不是更容易吗?
或者,如果您只想匹配最后一个
o
,请尝试使用模式o$
。但我真的认为你应该提供有关你的实际用例的更多信息。
Out of curiosity, why are you doing this?
This has not much to do with ruby, but with regular expressions.
Anyway, wouldn't it be easier to store the original string, so that you can restore it?
Alternatively, if you only want to match the last
o
, try to use the patterno$
.But I really think you should provide more info about your actual use-case.
如果您将
gsub
与正则表达式一起使用,就可以了。我相信这会做你想做的。
编辑
如果您知道该单词总是被空格、字符串开头或结尾包围,您可以使用类似以下内容的内容:
If you use
gsub
with a regular expression that would work.I believe that will do what you want.
EDIT
If you know that the word will always be surrounded with white space, beginning, or end of string you could use something like: