Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting some elements in a string using a regex

Tags:

regex

ruby

Context


Using Ruby I am parsing strings looking like this:

A type with an ID...

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

...with between 0 and n additional options separated with @...

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

In this example:

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

I want to retrieve:

  1. [Image=4b5da003ee133e8368000002@size:small@media:true]
  2. Image
  3. 4b5da003ee133e8368000002
  4. size:small
  5. media:true

Problem


Right now using this regex:

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

I get...

  1. [Image=4b5da003ee133e8368000002@size:small@media:true]
  2. Image
  3. 4b5da003ee133e8368000002
  4. @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 regex. Please use it if it can help you help me :)


Edit : if it's impossible to get all options separated, how could I get this:

  1. [Image=4b5da003ee133e8368000002@size:small@media:true]
  2. Image
  3. 4b5da003ee133e8368000002
  4. @size:small@media:true
like image 897
marcgg Avatar asked Feb 02 '26 14:02

marcgg


1 Answers

Edit:

Ruby's Regex implementation seems not to support multiple captures on one group, as most other regex engines do. Therefore, you'll have to do two steps; first getting all the @*:* in one string and then split those.

To get all of them, this should work:

(\[([a-zA-Z]+)=([a-zA-Z0-9]+)((?:@[a-zA-Z]+:[a-zA-Z]+)*)\])
like image 115
Lucero Avatar answered Feb 04 '26 06:02

Lucero



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!