Regular expression for dotted string with exception

I’m not sure that is it possible to do in one regex, but it doesn’t hurt to ask.

I created the expression:

/(?<variable>w+)((.(?<method>w+)((?<parameter>[^{}%]*)))|(.(?<subvariable>w+)))?/i

which helps me to “convert” dotted strings to arrays or call to methods:

core.settings => $core['settings'] 
core.set(param1, param2) => $core->set('param1', 'param2')

It works very well. But I have no idea how to build a several level expression which will work like this:

  1. string: core.settings
group <variable> = core  
group <subvariable> = settings
  1. string: core.get(param)
group <variable> = core
group <method> = get
group <parameter> = param
  1. string core.settings.time
group <variable> = core
group <subvariable> = settings.time
  1. string core.settings.time.set(param)
group <variable> = core
group <subvariable> = settings.time
group <method> = set
group <parameter> = param

Any ideas? And whether it is generally possible?

Answer

You can use

^(?<variable>w+)(?:.(?<subvariable>w+(?:.w+)*))??(?:.(?<method>w+)((?<parameter>[^{}%]*)))?$

See the regex demo.

Details:

  • ^ – start of string
  • (?<variable>w+) – Group “variable”: one or more word chars
  • (?:.(?<subvariable>w+(?:.w+)*))?? – zero or one occurrence of . and then Group “subvariable” matching one or more word chars followed with zero or more occurrences of a . and one or more word chars
  • (?:.(?<method>w+)((?<parameter>[^{}%]*)))? – an optional sequence of
    • . – a dot
    • (?<method>w+) – Group “method”: one or more word chars
    • ( – a ( char
    • (?<parameter>[^{}%]*) – Group “parameter”: zero or more chars other than {, }, %
    • ) – a ) char
  • $ – end of string.

Leave a Reply

Your email address will not be published. Required fields are marked *