ahmed.eltawil
ahmed.eltawil

Reputation: 571

Regular expression needed for this pattern: point(latitude,longitude)

I am trying to validate text that follows the pattern below:

Matching example:

Any help is greatly appreciated.

Thanks.

Upvotes: 3

Views: 1969

Answers (4)

Rohit Jain
Rohit Jain

Reputation: 213223

You can easily build your regex with a little bit of break-up here.

  • To match point( at the beginning, use - ^point\(
  • To match a latitude or longitude numbers, use - [-]?\d+(?:\.\d+)?
  • And again, to match ) at the end, use \)$.

For [-]?\d+(?:\.\d+)?, here's an explanation: -

  • [-]? - matches an optional negative (-) sign at the starting (? quantifier at the end means 0 or 1)
  • \d+ - matches one or more digits
  • (?:\.\d+)? - matches an optional decimal, followed by one or more digits. dot(.) is a special meta-character in Regex, so you need to escape it, if you want to match it.

Also, to limit your number of digits to 5, you can use - \d{1,5} instead of \d+, which matches minimum 1 and maximum 5 digits.

^(caret) and $(dollar) anchors matches the beginning and end of the string.

So, here's your regex: -

^point\([-]?\d+(?:\.\d{1,5})?,[-]?\d+(?:\.\d{1,5})?\)$

Upvotes: 4

csharptest.net
csharptest.net

Reputation: 64218

Something like this:

point\((?<lat>-?\d+\.\d{1,5}),(?<long>-?\d+\.\d{1,5})\)

Try using a regex tool, like expresso: http://www.ultrapico.com/Expresso.htm

Upvotes: 1

hall.stephenk
hall.stephenk

Reputation: 1165

Try this:

^point\(\-?\d+\.\d{1,5},\-?\d+\.\d{1,5}\)$
  • Must have the text "point(" at the beginning: ^point\(
  • Must follow it by a Latitude numerical value with up to 5 decimal places (example: 42.12345): \-?\d+\.\d{1,5}
  • Must follow it by a comma ",": ,
  • Must follow it by a Longitude numerical value with up to 5 decimal places (example: -81.12345): \-?\d+\.\d{1,5}
  • Must follow it by a closing parentheses ")": \)$

The latitude and longitude logic can be further broken up like this.

  • \-? = match on a negative sign if it exists (must escape with \ because - has special meaning in RegEx)
  • \d+ = match one or more decimal characters (i.e. 0 through 9)
  • \. = match the period (. alone has special meaning, must escape it)
  • \d{1,5} = match one to five decimal characters

Upvotes: 2

Julien May
Julien May

Reputation: 2051

how about:

^point\((\-?\d+(\.\d+)?),\s*(\-?\d+(\.\d+)?)\)$

Upvotes: 0

Related Questions