简体   繁体   中英

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]+

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

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]);

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM