Which regex expression will check GPS values?

I allow users to enter GPS values ​​through the 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 with PHP (using, possibly, preg_match() ), but since I am not very good at regular expression expressions (oh, dumb to me, I have to finally study it, I know), I don’t know know how to write an expression.

Obviously, this should be:
2x (numbers), 1x (period), 6x (numbers), 1x (comma), 2x (numbers), 1x (period), 6x (numbers)

Any suggestions on how to write this in regex?

+6
source share
5 answers

Sort of:

 /^(-?\d{1,2}\.\d{6}),(-?\d{1,2}\.\d{6})$/ 
  • ^ anchors at the beginning of input
  • -? Allows, but does not require, negative sign
  • \d{1,2} 1 or 2 decimal places required
  • \. decimal point required
  • \d{6} requires exactly 6 decimal digits
  • matches one comma
  • (repeat the first 5 bullets)
  • $ bindings at the end of input

I have included capturing parentheses so that you can extract individual coordinates. Feel free to omit them if you do not need it.

Useful regex link: http://www.regular-expressions.info/reference.html

+10
source

The other answers that I see do not take into account that longitude goes from -180 to 180, and latitude goes from -90 to 90.

The correct regular expression 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 regular expression spans at least -90 and not more than 90 for latitude, as well as at least -180 and not more than 180 in longitude, allowing them to place integers, as well as any number of decimal places from 1 to 6, if you want to allow more precision, just change {1,6} to {1, x}, where x is the number of decimal places

In addition, if you capture group 1, you will get latitude, and capture by group 2 will get longitude.

+13
source
 /$-?\d{2}\.\d{6},-?\d{2}\.\d{6}^/ 
+1
source

Turning around on another answer:

 /^-?\d\d?\.\d+,-?\d\d?\.\d+$/ 
+1
source

According to your example, this will do the following:

 if (preg_match('/(-?[\d]{2}\.[\d]{6},?){2}/', $coords)) { # Successful match } else { # Match attempt failed } 

Explanation:

 ( # Match the regular expression below and capture its match into backreference number 1 - # Match the character "-" literally ? # Between zero and one times, as many times as possible, giving back as needed (greedy) [\d] # Match a single digit 0..9 {2} # Exactly 2 times \. # Match the character "." literally [\d] # Match a single digit 0..9 {6} # Exactly 6 times , # Match the character "," literally ? # Between zero and one times, as many times as possible, giving back as needed (greedy) ){2} # Exactly 2 times 
0
source

Source: https://habr.com/ru/post/895363/


All Articles