Pilgrim
Pilgrim

Reputation: 573

regex to coordinates WGS84?

I'm trying this regular expressión, but I can't validate correctly the end white space and the letter:

/^\d{0,2}(\-\d{0,2})?(\-\d{0,2})?(\ ?\d[W,E]?)?$/

Examples of correct values:

  1. 33-39-10 N //OK
  2. 85-50 W //OK
  3. -85-50 E //Wrong

What's wrong?

Upvotes: 0

Views: 775

Answers (2)

The fourth bird
The fourth bird

Reputation: 163362

\d{0,2} this quantifier also matches a digit zero times so that would match the leading - in the 3rd example.

In the character class [W,E] you could omit the comma and list the characters you allow to match [ENW]

If only the third group is optional you could try including the whitespace before the end of the line $

^\d{2}(-\d{2})(-\d{2})? [ENW] $

Upvotes: 1

Alex
Alex

Reputation: 2232

I have used this regular expression : ^(?!\-)\d{0,2}?(\-\d{0,2}).+\s(N|E|W|S)$

Using a negative lookahead, we have excluded anything that starts with a dash (-).

  • (?!\-) = Starting at the current position in the expression, ensures that the given pattern will not match
  • \s(N|E|W|S) matches anything with a space (\s) and one of the letters using OR operator |.
  • You may also use \s+(N|E|W|S).
  • + = Matches between one and unlimited times, as many times as possible, giving back as needed

Upvotes: 0

Related Questions