开发者

removing certain escaped characters in ruby string using gsub and regex

I am dealing with some long strings in ruby which can have some weird escaped characters. For example, one string that is causing problems for me is like:

s = "foobar \240 \241 \242 foobar\nfoobar"
puts s
foobar ? ? ? foobar
foobar

I am trying to get rid of the weird \240, \241, \242 characters in the above string. Can someone tell me the regex for gsub that does that? Note: I want to retain the \n, just want to get rid of anything that has a backslash followed by a number.

Essentially, is there a way to get rid of all substrings of the form "\[one or more digits]"

Th开发者_开发知识库is quirk has been annoying me for a while now. I can do it for a given number, but cannot find the regex which makes a general substitution for any number after the backslash.


Use this regex: \\\d+. It matches \240, \241, \242.

It means Literal \, any digit one or more repetitions.


You can use the Regexp class to create a pattern for your specific range of characters and replace that.

s = "foobar \240 \241 \242 foobar\nfoobar"
min = 240
max = 242
pattern = Regexp.new "[\\#{min}-\\#{max}]"
puts s.gsub(pattern, '*')

will output:

foobar * * * foobar
foobar
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜