Getting some items in a string using regex

Context


Using Ruby I parse the lines as follows:

Type with identifier ...

[Image=4b5da003ee133e8368000002]
[Video=679hfpam9v56dh800khfdd32]

... between 0 and n optional parameters shared with @ ...

[Image=4b5da003ee133e8368000002@size:small]
[Image=4b5da003ee133e8368000002@size:small@media:true]

In this example:

[Image=4b5da003ee133e8368000002@size:small@media:true]

I want to receive:

  • [Image = 4b5da003ee133e8368000002 @ size: small @ media: true]
  • Picture
  • 4b5da003ee133e8368000002
  • size: small
  • Media: true

Problem


Right now using this regex:

(\[([a-zA-Z]+)=([a-zA-Z0-9]+)(@[a-zA-Z]+:[a-zA-Z]+)*\])

I get...

  • [Image = 4b5da003ee133e8368000002 @ size: small @ media: true]
  • Picture
  • 4b5da003ee133e8368000002
  • @media: true

What am I doing wrong? How can I get what I want?

PS: all the results are copied from http://rubular.com/ , which is nice to debug a regular expression. Please use it if it can help you help me :)


: , :

  • [ = 4b5da003ee133e8368000002 @: @: ]
  • 4b5da003ee133e8368000002
  • @Size: @:
+3
5

Edit:

Ruby Regex, , , . ; @*:* , .

, :

(\[([a-zA-Z]+)=([a-zA-Z0-9]+)((?:@[a-zA-Z]+:[a-zA-Z]+)*)\])
+3

"" , $4

/(\[([a-zA-Z]+)=([a-zA-Z0-9]+)((@[a-zA-Z]+:[a-zA-Z]+)*)\])/

split at.

:

#! /usr/bin/ruby

str = "[Image=4b5da003ee133e8368000002@size:small@media:true]"
if /(\[([a-zA-Z]+)=([a-zA-Z0-9]+)((@[a-zA-Z]+:[a-zA-Z]+)*)\])/.match(str)
  print $1, "\n",
        $2, "\n",
        $3, "\n",
        $4, "\n";

  $4[1..-1].split(/@/).each do |s|
    print s, "\n";
  end
end

:

[Image=4b5da003ee133e8368000002@size:small@media:true]
Image
4b5da003ee133e8368000002
@size:small@media:true
size:small
media:true
+2
(\[([a-zA-Z]+)=([a-zA-Z0-9]+)(?:@([a-zA-Z]+:[a-zA-Z]+))*\])

: true. , media: true : . , , , .

+1

, . , .

"a=b@c:d@e:f".split(/=|@/)

:

["a", "b", "c:d", "e:f"]

, ...

+1

, :

while (line = DATA.gets)
  line.chomp!

  if (m = line.match(/\[([a-zA-Z]+)=([a-zA-Z0-9]+)((?:@[a-zA-Z]+:[a-zA-Z]+)*)\]/))
    (type, hash, options) = m.to_a[1, 3]
    options = options.split(/@/).reject { |s| s.empty? }
    puts [ type, hash, options.join(',') ].join(' / ')
  end
end

__END__
[Image=4b5da003ee133e8368000002]
[Video=679hfpam9v56dh800khfdd32]
[Image=4b5da003ee133e8368000002@size:small]
[Image=4b5da003ee133e8368000002@size:small@media:true]
[Image=4b5da003ee133e8368000002@size:small@media:true@foo:bar]

:

Image / 4b5da003ee133e8368000002 / 
Video / 679hfpam9v56dh800khfdd32 / 
Image / 4b5da003ee133e8368000002 / size:small
Image / 4b5da003ee133e8368000002 / size:small,media:true
Image / 4b5da003ee133e8368000002 / size:small,media:true,foo:bar
+1

Source: https://habr.com/ru/post/1732049/


All Articles