import re
regex = re.compile(r"(?:implements|new|@var|extends)\s*(?P<fullNamespace>\\[A-Za-z]+|[A-Za-z]+?(?:\\(?P<class>[A-Za-z]+))+)")
test_str = ("<?php\n"
"declare(strict_types=1);\n\n"
"namespace Jerry\\QueryBuilder\\Builder;\n\n"
"use Jerry\\Interfaces\\QueryInterface;\n"
"use Jerry\\Interfaces\\Statements\\FilterInterface;\n"
"use Jerry\\QueryBuilder\\Statements\\Filters\\Where;\n\n"
"class Builder implements Jerry\\Interfaces\\BuilderInterface\\BuilderInterface extends Jerry\\Base\\Stuff\n"
"{\n"
" /** @var Jerry\\Interfaces\\ConnectorInterface\\Foo */\n"
" private $connection;\n\n"
" /** @var \\PDOStatement */\n"
" private $statement;\n\n"
" /** @var string */\n"
" private $sql;\n\n"
" /** @var QueryInterface */\n"
" private $query;\n\n"
" /** @var string */\n"
" private $filterSql;\n\n"
" /** @var array */\n"
" private $values;\n\n"
" public function __construct(Jerry\\Interfaces\\ConnectorInterface $connection)\n"
" {\n"
" $this->connection = $connection;\n"
" }\n\n"
" public function getResults(QueryInterface $query): array\n"
" {\n"
" $this->query = $query;\n"
" return [];\n"
" }\n\n"
" private function buildSql(): void\n"
" {\n"
" }\n\n"
" private function buildFilters(array $filters = [], string $filterSql = \"\"): void\n"
" {\n"
" if (! count($filters)) {\n"
" $filters = $this->query->getFilters();\n"
" }\n\n"
" $iterator = new \\ArrayIterator($filters);\n\n"
" while ($iterator->valid()) {\n"
" $filter = $iterator->current();\n\n"
" $iterator->next();\n"
" }\n"
" /** @var FilterInterface $filter */\n"
" foreach ($filters as $key => $filter) {\n"
" unset($filters[$key]);\n\n"
" if ($filter instanceof Where) {\n"
" // WHERE foo = bar\n"
" $filterSql .= \"WHERE ? ? ?\";\n"
" }\n"
" }\n"
" }\n\n"
" public function getConnection(): ConnectorInterface\n"
" {\n"
" $foo = new Jerry\\Interfaces\\ConnectorInterface();\n"
" return $this->connection;\n"
" }\n\n"
" public function setConnection(ConnectorInterface $connection): void\n"
" {\n"
" $this->connection = $connection;\n"
" }\n\n"
" public function getSql(): string\n"
" {\n"
" return $this->sql;\n"
" }\n"
"}")
matches = regex.finditer(test_str)
for match_num, match in enumerate(matches, start=1):
print(f"Match {match_num} was found at {match.start()}-{match.end()}: {match.group()}")
for group_num, group in enumerate(match.groups(), start=1):
print(f"Group {group_num} found at {match.start(group_num)}-{match.end(group_num)}: {group}")
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Python, please visit: https://docs.python.org/3/library/re.html