tags:

views:

101

answers:

6

I can't figure this out:

22.584\r\n\t\t\tl-6.579-22

I want to match the "\r\n\t\t\t" and replace with a single space " ". Problem is the number of "\t", "\r", and "\n" fluctuates, as do the surrounding characters.

Help!

+4  A: 

s/\s+/ /g

s/(?:\\[rnt])+/ /g
KennyTM
Nope. Doesn't work.
neezer
@neezer, note that `\s` matches more than just `\t`, `\r` or `\n`. It matches (in most cases) these: `[ \t\n\x0B\f\r]`, but that may be fine with you of course.
Bart Kiers
@neezer: What language are you using?
KennyTM
@neezer: In what way doesn't it work? Does it give an error? Does it replace too much? Too little? Does it do nothing at all?
Mark Byers
I'm using Ruby. It doesn't match anything. The values in the string in my question are not escape values (as in, to match, you'd search for `\\r` or the like).
neezer
@neezer: See update (I didn't translate it to Ruby.)
KennyTM
Your edit matches them individually, not the group. I need to replace the whole group with a single space. Any other thoughts?
neezer
Whoops... nevermind. For the "+". That works.
neezer
I think this is the correct idiom for replacing a sequence of whitespace characters with a space. It matches all possible whitespace, not just \r, \t and \n, it matched a sequence of one or more, and it does a global replace rather than just replacing the first such sequence. The only tricky bit is making the regexp apply to the whole string rather than one line at a time, otherwise you get left with \n's in your input.
liwp
A: 

In PHP:

preg_replace("/(?:\\\[trn])+/", " ", $str);
kemp
did you see this was a ruby question?
glenn jackman
When I answered there was no mention of ruby, or any other language. The post was edited later, as you can see. Also, accepted answer uses Perl's syntax.
kemp
A: 
sed 's/\\[rnt]/ /g;s/  */ /g'
mouviciel
A: 
'22.584\r\n\t\t\tl-6.579-22'.gsub(/(\\[rnt])+/, ' ')
psyho
A: 
#!/usr/bin/ruby1.8

s = "22.584\r\n\t\t\tl-6.579-22"
p s                           # => "22.584\r\n\t\t\tl-6.579-22"
p s.gsub(/[\r\n\t]+/, ' ')    # => "22.584 l-6.579-22"
Wayne Conrad
A: 

I'd treat the CR-NL as one atom:

str.gsub!(/(?:\r\n)+\t+/, ' ')
glenn jackman