Need help on Regex

Hi,

I wrote the below Regex:

[“D123456xct67”,“D123456233xct67”,“123456xct67”,“2D123456xct67”,“788123456xct67”].map{|e|
e[/^([A-Z]\d{5})|^([A-Z]\d{8})|^(\d{9})|^(\d{6})/] }

=> [“D12345”, “D12345”, “123456”, nil, “788123456”]

The above regex not working.

Rules are :

(a) select the 6 digits number from the beginning or 9 digits. Examples
“123456789” -> “123456789”
“1234567895” -> “123456789”
“12345678” -> nil
“12345” -> nil
(b) select the first 6 or 9 characters. Examples

“A123654” -> “A12365”
“A123651258YT7889” -> “A12365125”
“A1233Ty6788” -> nil
“A12365125” - > “A12365125”
“A123651Yu7 -> nil”

You can also try: http://rubular.com

I wouldn’t use a single regex to solve this - I’d use multiple checks
and if statements. I’d try to give you an example if I could understand
your rules, you’re not clear about when to follow which rules.

Try this tool out it will help you build your regex in a ui.

On Tue, Sep 17, 2013 at 2:09 AM, Leslie V. [email protected]
wrote:

You can also try: http://rubular.com

I wouldn’t use a single regex to solve this - I’d use multiple checks
and if statements. I’d try to give you an example if I could understand
your rules, you’re not clear about when to follow which rules.

I think this is intended:

irb(main):001:0>
[“D123456xct67”,“D123456233xct67”,“123456xct67”,“2D123456xct67”,“788123456xct67”].map{|e|
irb(main):002:1* e[/\A\d{6}(?:\d{3})?/] || e[/\A.{6}(?:.{3})?/]}
=> [“D123456xc”, “D12345623”, “123456”, “2D123456x”, “788123456”]

combined:

irb(main):005:0>
[“D123456xct67”,“D123456233xct67”,“123456xct67”,“2D123456xct67”,“788123456xct67”].map{|e|
irb(main):006:1* e[/\A(?:\d{6}(?:\d{3})?|.{6}(?:.{3})?)/]}
=> [“D123456xc”, “D12345623”, “123456”, “2D123456x”, “788123456”]

Cheers

robert

Just commenting on this whole thread.

+1 for Rubular – it is a great tool to have.

I haven’t heard of RegExr before – it is interesting, but I haven’t
played much with it yet.

If you’re curious, check out my own project:

Cheers,
Hal

On Tue, Sep 17, 2013 at 12:58 AM, Robert K.