# Regular expression reformating a value

I am not really sure how to do this. I have a series of number that need
parsed. Strip the zeros, if a caret
exists replace it with a slash.

1.) 000123^2 - should be 123/2
2.) 1^2 - should be 1/2
3.) 0001 - should be 1
4.) 000123 - should be 123

I do not know how to do the condtional to exclude the slash on examples
3
and 4. How do I prevent the addition of the slash when there is no caret
in
the number?

reg = /(?:[1-9]{1}\d*)\W(?:\d*)/

puts reg.match(“000123^2”);

puts reg.match(“123^2”);

puts reg.match(“0001”);

puts reg.match(“000123”);

puts reg.match(“123”);

Thanks!

On 9/28/06, Steven K. [email protected] wrote:

4.) 000123 - should be 123
How about
s.sub!(/^\s0+/,"").sub(/^/,"/")
than
if you need checking
%r{^\s
[0-9/]+} === s
which is not completely strict because of
5.) 12^34/5

Cheers
Robert

Deux choses sont infinies : l’univers et la bÃªtise humaine ; en ce qui
concerne l’univers, je n’en ai pas acquis la certitude absolue.

• Albert Einstein

What I am looking for is a single regex to accomplish this so I can
avoid
the parsing afterwards.

I would like to break the string into groups then reformat the string
with
some regex conditional logic. Is this possible?

Thanks!

Steve

Perfect!

Thanks!

Steve

On Fri, 2006-09-29 at 00:51 +0900, Steven K. wrote:

I am not really sure how to do this. I have a series of number that need
parsed. Strip the zeros, if a caret
exists replace it with a slash.

1.) 000123^2 - should be 123/2
2.) 1^2 - should be 1/2
3.) 0001 - should be 1
4.) 000123 - should be 123

Only lightly tested, but does this do what you’re after?

“000123^2”.gsub(/(^0+)?(\d*)(^)?/) { “#{\$2}#{’/’ if \$3}” }

# => “123/2”

“1^2”.gsub(/(^0+)?(\d*)(^)?/) { “#{\$2}#{’/’ if \$3}” }

# => “1/2”

“0001”.gsub(/(^0+)?(\d*)(^)?/) { “#{\$2}#{’/’ if \$3}” }

# => “1”

“000123”.gsub(/(^0+)?(\d*)(^)?/) { “#{\$2}#{’/’ if \$3}” }

# => “123”

I’m assuming you mean only leading zeroes, e.g:

“0001^0001^1”.gsub(/(^0+)?(\d*)(^)?/) { “#{\$2}#{’/’ if \$3}” }

# => “1/0001/1”

If that’s not what you want, I think you could strip all the leading
zeroes with a small change:

“0001^0001^1”.gsub(/(0+)?(\d*)(^)?/) { “#{\$2}#{’/’ if \$3}” }

# => “1/1/1”

Hope that helps,

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs