I'm letting users enter GPS values through a form, they all have the same form, some examples:
49.082243,19.302628
48.234142,19.200423
49.002524,19.312578
I want to check the entered value using PHP (using preg_match()
, I guess), but as I'm not good in regex expressions (oh, dumb me, I should finally learn it, I know), I don't know how to write the expression.
Obviously it should be:
2x (numbers), 1x (dot), 6x (numbers), 1x (comma), 2x (numbers), 1x (dot), 6x (numbers)
Any suggestions how to write this in regex?
The latitude and longitude, if present will always appear in the form of (X, Y) where X and Y are decimal numbers. For a valid (latitude, longitude) pair: -90<=X<=+90 and -180<=Y<=180. They will not contain any symbols for degrees or radians or N/S/E/W.
Regular Expressions, or RegEx, is a sequence of characters that defines a search pattern. As a UiPath RPA Developer, we use RegEx to extract data out of, e.g., emails and PDFs. Learning is necessary, as RPA is about extracting data from one system and placing them in another.
Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1. 1* means any number of ones.
With regex you have a couple of options to match a digit. You can use a number from 0 to 9 to match a single choice. Or you can match a range of digits with a character group e.g. [4-9]. If the character group allows any digit (i.e. [0-9]), it can be replaced with a shorthand (\d).
The other answers I see don't take into account that longitude goes from -180 to 180 and latitude goes from -90 to 90.
The proper regex for this would be (assuming the order is "latitude, longitude"):
/^(-?[1-8]?\d(?:\.\d{1,6})?|90(?:\.0{1,6})?),(-?(?:1[0-7]|[1-9])?\d(?:\.\d{1,6})?|180(?:\.0{1,6})?)$/
This regex covers having no less than -90 and no more than 90 for latitude as well as no less than -180 and no more than 180 for longitude while allowing them to put in whole numbers as well as any number of decimal places from 1 to 6, if you want to allow greater precision just change {1,6} to {1,x} where x is the number of decimal place
Also, if you capture on group 1 you get the latitude and a capture on group 2 gets the longitude.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With