regex - PHP not respecting non-capturing group with lookahead with a capturing group inside -
i have php regex match:
preg_match_all('/(\d+)(?:\.(?=(\d+)))?/', "43.3", $matches, preg_set_order); which (at least in mi mind) means:
match 1 or more numbers group, , if there '.' after group followed group of numbers, match too, ignore '.'. so, possible strings be:
1 23244 24.5 2.454646 but not:
1. now, works in regex101.com test string throw @ it, doesn't seem working php. if var_dump($matches):
array(2) { [0]=> array(3) { [0]=> string(3) "43." [1]=> string(2) "43" [2]=> string(1) "3" } [1]=> array(2) { [0]=> string(1) "3" [1]=> string(1) "3" } } - why getting point after
43? - why getting duplicated?
- why getting
3inside first group?
the first match full match, though whole pattern wrapped in set of parentheses. don't think can turn off.
you're getting 3 in first group because you've got 2 (\d+)'s in pattern. remove parentheses 1 after ?= if don't want it.
if want full number, can try this:
>>> preg_match_all('/(?<!\d)\d+(?:\.\d+)?(?![\d.])/', "43.3 31.52 1.", $matches); => 2 >>> $matches => [ [ "43.3", "31.52" ] ] if there's 1 number, should use preg_match, not preg_match_all. e.g.
>>> preg_match_all('/(\d+)(?:\.(\d+))?/', "43.3", $matches) => 1 >>> $matches => [ [ "43.3" ], [ "43" ], [ "3" ] ] you can array_shift off full match.
Comments
Post a Comment