简体   繁体   English

在正则表达式结束时Php前瞻性断言

[英]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 我想写一个带有断言的正则表达式从字符串unknownstring/55.1提取数字55,这是我的正则表达式

    $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. 所以,基本上我想说的是给我斜线后面的数字,然后是一个点和数字1,之后就没有字符了。 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, eg unknow/545.1nstring/55.1 . 但是这个条件是必不可少的,因为我需要将它作为字符串的结尾,因为unknownstring部分可以包含类似的文本,例如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. 也许我可以使用preg_match_all,并采取最后一场比赛,但我想了解为什么第一个正则表达式不起作用,我的错误在哪里。

Thanks 谢谢

Use anchor $ inside lookahead: $ lookahead中使用anchor $

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

RegEx Demo RegEx演示

You cannot use $ outside the positive lookahead because your number is NOT at the end of input and there is a \\.1 following it. 你不能在积极的前瞻之外使用$ ,因为你的数字不在输入的末尾,并且后面有一个\\.1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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