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

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

java - Digest auth with Spring Security using javaconfig -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -