T
T
Tant2011-07-29 09:05:40
PHP
Tant, 2011-07-29 09:05:40

RegExp task

Faced such task: there is a line in which arbitrary pieces of text can be contained in brackets. You need to select all four-digit numbers (years) that are outside the brackets.
For example, from the line:

$text = "(P. 1: 15. X. 1481; P. 2: 4. XII. 1482); P. 3: 18. II. 1483;
 P. 4: 10. VI. 1484; P. 5: 10. VI. 1485; (P. 6: 6. IX. 1486; P. 7: 17. VII. 1487);
 P. 8: 17. VII. 1480";

you need to select the values ​​1483, 1484, 1485, 1480.

Killed a lot of time trying to solve this with one RegExp - nothing.
I had to split it into two steps:
$pattern = "/\(.*\)/U";
$r = preg_replace($pattern, '', $text);
$pattern = "/\d{4}/";
preg_match_all($pattern, $r, $matches);
print_r($matches[0]);

Was it possible to get by with one expression?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
W
Wott, 2011-07-29
@Tant

Sent you rightto positional checks
The point is to exclude the condition that the numbers are inside brackets, that is, we introduce a check for the absence of a closing bracket in front (?! . * \) ) . But the problem is that we can capture a pair of parentheses in front in this way. To avoid this case, instead of any character, we are looking for everything except the opening bracket - (?! [ ^ \( ] * \) )
The final regexp looks like this: / \d { 4 } (?! [ ^ \( ] * \) ) /

D
DorBer, 2011-07-29
@DorBer

Using positional checks

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question