Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Got "two named subpatterns have the same name" when combining 2 regex into one

Tags:

regex

php

I'm trying to combine 2 different regex with the same names into one and got the error message like this:

Warning: preg_match(): Compilation failed: two named subpatterns have the same name at offset 276 ...

One regex looks like this:

'%<div class="artikkelen">[\s\S]*?<h2>(?P<title>[\s\S]*?)</h2>%'

The other looks like this:

'%<div id="article">[\s\S]*?<h1>(?P<title>[\s\S]*?)</h1>%'

I could combine them in the following way without problem:

'%(<div class="artikkelen">[\s\S]*?<h2>(?P<title>[\s\S]*?)</h2>|<div id="article">[\s\S]*?<h1>(?P<title2>[\s\S]*?)</h1>)%'

But I don't like this way because I use 2 names. I'm wondering whether there is a better way to solve this problem. Thanks in advance.

Best Regards, Box (boxoft...Simple & Great)

like image 524
boxoft Avatar asked Sep 14 '09 09:09

boxoft


1 Answers

I found this page looking for a way to have two (or more?) named subpatterns with the same name, and I found this page with the answer (relevant excerpt here)

Duplicate names

If you are using named patterns you can now have the same name multiple times, provided you put the "(?J)" option in your pattern. For example:

    Match: (?J)(?P<name>Ni.+)|(?P<name>Fr.+)

This would match "Nick" or "Fred", and whichever one matched, the named pattern "name" would be set to it.

just contributing knowledge back to the universe

like image 124
Electric Darrell Avatar answered Oct 12 '22 12:10

Electric Darrell