Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php lookahead assertion at the end of the regex

I want to write a regex with assertions to extract the number 55 from string unknownstring/55.1, here is my regex

    $str = 'unknownstring/55.1';
    preg_match('/(?<=\/)\d+(?=\.1)$/', $str, $match);

so, basically I am trying to say give me the number that comes after slash, and is followed by a dot and number 1, and after that there are no characters. But it does not match the regex. I just tried to remove the $ sign from the end and it matched. But that condition is essential, as I need that to be the end of the string, because the unknownstring part can contain similar text, e.g. unknow/545.1nstring/55.1. Perhaps I can use preg_match_all, and take the last match, but I want understand why the first regex does not work, where is my mistake.

Thanks

like image 678
dav Avatar asked Oct 19 '22 20:10

dav


1 Answers

Use anchor $ inside lookahead:

(?<=\/)\d+(?=\.1$)

RegEx Demo

You cannot use $ outside the positive lookahead because your number is NOT at the end of input and there is a \.1 following it.

like image 91
anubhava Avatar answered Oct 22 '22 12:10

anubhava