regex - find matches for positive and negative number in arithmetic expression -
given following arithmetic expression: -1-5+(-3+2)
there need find matches positive , negative numbers. expression expected result is: -1 5 -3 2
i tried use regex -?\d+(.\d+)? returns: -1 -5 -3 2 -5 not correct.
is possible build regex pattern positive , negative numbers case , other similar cases ?
you can use
(?<!\d)[-]?\d*\.?\d+ see regex demo
pattern details:
(?<!\d)- negative lookbehind fails match if digit appears before tested position[-]?- optional (1 or 0) minus sign\d*- 0+ digits\.?- 1 or 0 dots (a literal dot escaped)\d+- 1+ digits
note \d*\.?\d+ allows .456 values, if not need that, use \d+(?:\.\d+)?.
if lookbehind not supported, use capturing group alternation check if - not @ start of string or before digit:
(?:^|\d)([-]?\d*\.?\d+) see another demo (the necessary value in group 1).
Comments
Post a Comment