Regex to match a , and seperate

irb(main):007:0> str =
"server[1,2].localhost.com,server[2-5].localhost.com,server1.localhost.com"
=>
"server[1,2].localhost.com,server[2-5].localhost.com,server1.localhost.com"

irb(main):008:0> str.scan %r{(?:[^,\[\]]+|\[[^\]]*\])+}
=> ["server[1,2].localhost.com", "server[2-5].localhost.com",
"server1.localhost.com"]

Now, if you want to be safe against multiple nesting levels you can use
recursive matching:

irb(main):033:0> str =
"server[1,2].localhost.com,server[2-5[3-9]].localhost.com,server1.localhost.com"
=>
"server[1,2].localhost.com,server[2-5[3-9]].localhost.com,server1.localhost.com"

irb(main):034:0> str.scan( %r{ (?<name> (?: [^,\[\]]+ | (?<gr> \[ (?:
[^\[\]] | \g<gr> )* \] ) )+ ) }x ).map { $~[:name] }
=> ["server1.localhost.com", "server1.localhost.com",
"server1.localhost.com"]

with a bit friendlier formatting

irb(main):046:0* str.scan(
irb(main):047:1* %r{
irb(main):048:1/ (?<name>
irb(main):049:1/ (?:
irb(main):050:1/ [^,\[\]]+
irb(main):051:1/ | (?<gr> \[ (?: [^\[\]]+ | \g<gr> )* \] )
irb(main):052:1/ )+
irb(main):053:1/ )
irb(main):054:1/ }x ).map { $~[:name] }
=> ["server1.localhost.com", "server1.localhost.com",
"server1.localhost.com"]

or (basically the same regexp without the outer named group):

irb(main):035:0> str.scan %r{ (?: [^,\[\]]+ | (?<gr> \[ (?: [^\[\]]+ |
\g<gr> )* \] ) )+ }x do puts $& end
server[1,2].localhost.com
server[2-5[3-9]].localhost.com
server1.localhost.com
=>
"server[1,2].localhost.com,server[2-5[3-9]].localhost.com,server1.localhost.com"

SCNR :slight_smile:

Cheers

robert

ยทยทยท

--
Posted via http://www.ruby-forum.com/.