2

I have a problem involving PHP and regex.

I have some files and need to capture some of the names. But there's one part that are not in all.

Example files:
D.SAE.IND.001.TME.BR.SER.20120729
D.SUI.IND.003.TMC.GER.TOT.201206
D.SAE.LIS.008.AGE.APS.SER.45D.20120713

Note that the last file has a part ("45D") that is optional.
I need to get every group. I was using the following regex:

preg_match('/D\.(?P<font>[\w]*)\.(?P<tipo>[\w]*)\.(?P<numberLevel>[\d]*)\.(?P<indicator>[\w]*)\.(?P<nameLevel>[\w]*)\.(?P<group>[\w]*)\.(?P<id>[\d]*)/i', $arrInput , $result);

The problem is that optional part (eg the latest file - "45D").
I need this result:

D.SAE.IND.001.TME.BR.SER.20120729
$result['fonte'] = 'SAE'
$result['tipo'] = 'IND'
$result['numberLevel'] = '001'
$result['indicator'] = 'TME'
$result['nameLevel'] = 'BR'
$result['group'] = 'SER'
$result['op'] = ''
$result['id'] = '20120729'

D.SAE.LIS.008.AGE.APS.SER.45D.20120713
$result['fonte'] = 'SAE'
$result['tipo'] = 'LIS'
$result['numberLevel'] = '008'
$result['indicator'] = 'AGE'
$result['nameLevel'] = 'APS'
$result['group'] = 'SER'
$result['op'] = '45D'
$result['id'] = '20120713'

Thank you in advance for help.

2 Answers 2

8

Why don't you just use explode('.', $string)?

You can count the array to see the number of entries. If it's 7, you know you are missing the optional string.

Sign up to request clarification or add additional context in comments.

3 Comments

+1 I love switching from a regex to explode! Two birds with one stone :)
thanks. It's a great idea. But, only for curiosity: is possible with regex?
@NakaBr probably.. If you'd like to do it as an exercise you can try. Check out the other answer too!
4

This works for me:

/D\.(?P<font>[\w]*)\.(?P<tipo>[\w]*)\.(?P<numberLevel>[\d]*)\.(?P<indicator>[\w]*)\.(?P<nameLevel>[\w]*)\.(?P<group>[\w]*)\.(?:(?P<op>.*)\.)?(?P<id>[\d]*)/i

The key is adding:

(?:(?P<op>.*)\.)?

Before the id group.

Edit: Added the ?: to make the grouping non-capturing.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.