Regexp to extract number with hyphen

I have a text with “foo 01-02” in a string. I want to extract foo
01-02 using regexp. reg = /foo (\d+)/ only extracts foo with numbers
when there is no hyphen.

reg = /foo (\d{1,})|(-)|(\d{1,})/ only extracts foo 01. TIA.

[email protected] wrote:

I have a text with “foo 01-02” in a string. I want to extract foo
01-02 using regexp. reg = /foo (\d+)/ only extracts foo with numbers
when there is no hyphen.

reg = /foo (\d{1,})|(-)|(\d{1,})/ only extracts foo 01. TIA.

Does this work?

/foo (\d±\d+)/

On 5/29/07, [email protected] [email protected] wrote:

I have a text with “foo 01-02” in a string. I want to extract foo
01-02 using regexp. reg = /foo (\d+)/ only extracts foo with numbers
when there is no hyphen.

reg = /foo (\d{1,})|(-)|(\d{1,})/ only extracts foo 01. TIA.

“foo 01-02” =~ /(\d+)-(\d+)/

puts $1 #=> “01”
puts $2 #=> “02”

The regexp: /foo\ (\d+)-?(\d*)/
seems to work. Still testing…

On Wed, May 30, 2007 at 08:15:05AM +0900, [email protected] wrote:

The regexp: /foo\ (\d+)-?(\d*)/
seems to work. Still testing…

What exactly are the allowed matches? Only num1-num2, or is num1 by
itself
allowed? What about num1-num2-num3?

/foo ([0-9-]+)/ matches …foo 1-2-3… and foo 1-2 and foo 1
/foo (\d±\d+)/ matches …foo 1-2… only
/foo (\d+(-\d+)?)/ matches …foo 1-2… and foo 1, but not
foo-1-2-3

On Wed, May 30, 2007 at 10:40:09PM +0900, Ken B. wrote:

Others have suggested the following correction:
/(\d+)-?(\d+)/

That particular example matches 11, but not 1.

The most important thing is to be clear about exactly what you want to
allow
to match or not match; then writing the regexp is easy.

On Tue, 29 May 2007 15:45:34 -0700, [email protected] wrote:

I have a text with “foo 01-02” in a string. I want to extract foo 01-02
using regexp. reg = /foo (\d+)/ only extracts foo with numbers when
there is no hyphen.

reg = /foo (\d{1,})|(-)|(\d{1,})/ only extracts foo 01. TIA.

That’s because the | operator in a regexp means either-or. So you’re
matching
foo (\d{1,})
or you’re matching
(-)
or you’re matching
(\d{1,})
but not all three at the same time.
Others have suggested the following correction:
/(\d+)-?(\d+)/

–Ken

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