Correct Use of Matcher Groups in Java Regex when using logical OR -


i have parse string contains latitude & longitude values. strings can in 1 of 2 formats:

lat: 33.1234 lon: -110.1234 lat, lon: 33.1234 -110.1234 

i'm using pattern & matcher in java. following regex matches either string correctly:

lat, long:\s*([-\d\.]+)[\,\s]+([-\d\.]+)|lat:\s*([-\d\.]+)\s*lon[g]?:\s*([-\d\.]+) 

however...the matcher has 4 groups. either first 2 groups or second 2 groups have lat/lon values , other 2 null.

i realize can test null ... curious if there's way have matcher return 2 groups containing lat & lon values regardless of string format given?

this regex matches 2 sample cases.

lat(?:,\s+long?)?:\s*([-\d\.]+)(?:\s+|\s*,\s*)(?:long?:\s+)?([-\d\.]+)

https://regex101.com/r/d3abpx/1

 lat                           # lat label  (?: , \s+ long? )?            # optional , long label  :                             # colon  \s*                           # optional space  ( [-\d\.]+ )                  # (1), lat value  (?: \s+ | \s* , \s* )         # seperated space or comma ( must have 1 )  (?: long?: \s+ )?             # optional long label , colon  ( [-\d\.]+ )                  # (2), long value 

Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -