masay
masay

Reputation: 933

regex for weird string

I need to help about writing regex for below string. I have tried lots of pattern but all failed. I have a string like

package1[module11,module12,module13],package2[module21,module22,module23,module24,module25],package3[module31]

and I want to split this string like

package1
module11,module12,module13
package2
module21,module22,module23,module24,module25
package3
module31

I know it is weird to ask a regex from here but ...

Upvotes: 1

Views: 71

Answers (1)

Kobi
Kobi

Reputation: 138137

You can match using the pattern:

(\w+)\[(\w+(?:,\w+)*)\]

Example: http://www.rubular.com/r/rPUEWBoU1d

The pattern is pretty simple, really:

  • (\w+) - capture the first word (package1)
  • \[
  • (\w+(?:,\w+)*) - A sequence of at least one word (module11), followed by comma separated words (assuming they are well formed)
  • \]

In all cases, you may want to change \w to your alphabet (maybe even [^,\[\]] - not comma or brackets). You also may want to check the whole string matches, as the above pattern may skip over unwanted parts (for example: a[b]$$$$c[d])

Upvotes: 4

Related Questions