Regexp to extract number with hyphen

B

bcparanj

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.
 
T

Tim Hunter

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+)/
 
T

Tim Pease

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"
 
K

Ken Bloom

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
 
B

Brian Candler

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
 
B

Brian Candler

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,260
Messages
2,571,308
Members
47,956
Latest member
AmeeBerger

Latest Threads

Top