Kiksy
Kiksy

Reputation: 1292

Regex PHP - dont match specific string followed by numeric

Im looping over a large number of files in a directory, and want to extract all the numeric values in a filename where it starts lin64exe , for instance, lin64exe005458002.17 would match 005458002.17. I have this part sorted, but in the directory there are other files, such as part005458 and others. How can I make it so I only get the numeric (and . ) after lin64exe ?

This is what I have so far:

[^lin64exe][^OTHERTHINGSHERE$][0-9]+

Upvotes: 1

Views: 82

Answers (3)

Braj
Braj

Reputation: 46891

You can try with look around as well

(?<=^lin64exe)\d+(\.\d+)?$

Here is demo

Pattern explanation:

  (?<=                     look behind to see if there is:
    ^                        the beginning of the string
    lin64exe                 'lin64exe'
  )                        end of look-behind

  \d+                      digits (0-9) (1 or more times (most possible))
  (                        group and capture to \1 (optional):
    \.                       '.'
    \d+                      digits (0-9) (1 or more times (most possible))
  )?                       end of \1

  $                        the end of the string

Note: use i for ignore case

sample code:

$re = "/(?<=^lin64exe)\\d+(\\.\\d+)?$/i";
$str = "lin64exe005458002.17\nlin64exe005458002\npart005458";

preg_match_all($re, $str, $matches);

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174874

Regex to match the number with decimal point which was just after to lin64exe is,

^lin64exe\K\d+\.\d+$

DEMO

<?php
$mystring = "lin64exe005458002.17";
$regex = '~^lin64exe\K\d+\.\d+$~';
if (preg_match($regex, $mystring, $m)) {
    $yourmatch = $m[0]; 
    echo $yourmatch;
    }
?> //=> 005458002.17

Upvotes: 2

anubhava
anubhava

Reputation: 786359

You can use this regex and use captured group #1 for your number:

^lin64exe\D*([\d.]+)$

RegEx Demo

Code:

$re = '/^lin64exe\D*([\d.]+)$/i'; 
$str = "lin64exe005458002.17\npart005458"; 

if ( preg_match($re, $str, $m) )
    var_dump ($m[1]);

Upvotes: 1

Related Questions