简体   繁体   中英

Match 2 groups of numbers separated by specific characters

Say I have a few strings, such as:

N00E001 N00W001 N00E002

What would be the best regex to find both groups of numbers in each string?

I'm not the best with regex. Here's what i'm currently working with: (\\d+)[W|E](\\d+) .

"(\d+)[W|E](\d+)"

would also match "N00|001" .

So

"(\d+)[WE](\d+)"

should do fine.

If you have always the exact same format, you could use a more restrictive regex :

"\A[NS]\d{2}[WE]\d{3}\Z"

This would match :

  • a N or a S
  • followed by 2 digits
  • followed by E or W
  • followed by 3 digits

The whole match should be the complete string. "Location N00W001" wouldn't match, for example.

Test

import re

strings = ["N00E001", "N00W001", "N00E002"]

pattern = re.compile("\A[NS]\d{2}[WE]\d{3}\Z")

print all(pattern.match(string) for string in strings)
# True

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM