paulie.jvenuez
paulie.jvenuez

Reputation: 295

Match pattern, exclude everything else

I have some data that looks like the following.

\\0101 \\0102 \\0103 \\0104
\\0201 \\0202 \\0203 \\0204 \\0205 \\0206
\\0301 \\0302 \\0303 \\0304 \\0305 \\0306

I need to always get the digits before the last \\ in the line.

So in the above lines, my output should be.

0103
0205
0305

I am matching these digits, but its also matching the last set.

(?<=\\\\)\d+(?: \\\\\d+$)

How can I exclude everything else except those digits?

Upvotes: 1

Views: 75

Answers (3)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89639

If your data are always in the same form, the lookbehind is useless. You can try this:

$subject = <<<'LOD'
\\0101 \\0102 \\0103 \\0104
\\0201 \\0202 \\0203 \\0204 \\0205 \\0206
\\0301 \\0302 \\0303 \\0304 \\0305 \\0306
LOD;

preg_match_all('~\d+(?=\D+\d+$)~m', $subject, $matches);

print_r($matches);

Upvotes: 2

Enissay
Enissay

Reputation: 4953

There's a many ways to do that, but to correct your regex, just add a capturing group on the target digits

(?<=\\\\)(\d+)(?: \\\\\d+$)

Live DEMO

And another one (wich could be simplified more):

\\\\(\d+)\s+[\d\\]+$

Live DEMO

Upvotes: 3

hwnd
hwnd

Reputation: 70750

You were close, instead of using a non-capturing group (?: use a Positive Lookahead.

(?<=\\\\)\d+(?= +\\\\\d+$)

See live demo

Upvotes: 3

Related Questions