开发者

Regexp look-behind to match internet speeds

So the user may search for "10 mbit" after which I want to capture the "10" so I can use it in a speed-search rather than a string-search. This isn't a problem, the below regexp does this fine:

if (preg_match("/(\d+)\smbit/", $string)){ ... }

But, the user may search for something like "10/10 mbit" or "10-100 mbit". I don't want to match those with the above regexp - they should be handled in another fashion. So I would like a regexp that matches "10 mbit" if the number is all-numeric as a whole word (i.e. contained by whitespace, newline or lineend/linestart)

Using lookbehind, I did this:

if (preg_match("#(?<!/)(\d+)\s+mbit#i", $string)){

Just to catch those that doesn't have "/" before them, but this matched true for this strin开发者_C百科g: "10/10 mbit" so I'm obviously doing something wrong here, but what?


If the slash or hyphen is the only thing you care about, this should do it:

'#(?<![\d/-])(\d+)\s+mbit#i`

The problem with your regex is that \d+ is only required to match one digit. It can't match the 10 in 10/10 mbit because it's preceded by a slash, but the 0 isn't. To make sure it matches from the beginning of the number, you have to include \d in the list of things it can't be preceded by.


You lookback assertion is negative. It tells the string should not be preceded by /

So the / is matched inside the string (as the regex cannot match only "10" : you forbid it explicitely with the assertion). Maybe you wanted a positive lookbehind?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜