How to match characters only if preceded by (positive lookbehind)

Viewed 28

I want to match a latitude and longitude entry, separated by comma and possibly with a name:

what should match

-43.48394, 87.394886
-43.44884, 88.344774, home
-43.87778, 88.987566,

what should not match

-43.89987, 89.345434 home
-43.44884, 88.344774, home, restaurant 

This is what I've tried,

^(-?\d+(\.\d+)?),\s*(-?\d+(\.\d+)?),?(?<=,)[a-zA-Z ]*$

but fails to match

-43.48394, 87.394886

what am I missing here?

Thanks

1 Answers

The -43.48394, 87.394886 string is not matched because you require a comma to appear after a longitude value. The ,?(?<=,) part is equal to just , because this pattern matches an optional comma that is followed by a position that must be preceded with a comma.

You can use

^(-?\d+(?:\.\d+)?),\s*(-?\d+(?:\.\d+)?)(?:,[a-zA-Z ]*)?$

See the regex demo.

Details:

  • ^ - start of string
  • (-?\d+(?:\.\d+)?) - Group 1: optional -, one or more digits and then an optional sequence of a dot and one or more digits
  • , - a comma
  • \s* - zero or more whitespaces
  • (-?\d+(?:\.\d+)?) - Group 2: optional -, one or more digits and then an optional sequence of a dot and one or more digits
  • (?:,[a-zA-Z ]*)? - an optional sequence of a comma and then zero or more letters or spaces
  • $ - end of string.
Related