简体   繁体   English

匹配由特定字符分隔的2组数字

[英]Match 2 groups of numbers separated by specific characters

Say I have a few strings, such as: 说我有一些字符串,例如:

N00E001 N00W001 N00E002 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+)

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

would also match "N00|001" . 也将匹配"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 N或S
  • followed by 2 digits 后跟2位数字
  • followed by E or W 其次是E或W
  • followed by 3 digits 后跟3位数字

The whole match should be the complete string. 整个匹配项应该是完整的字符串。 "Location N00W001" wouldn't match, for example. "Location N00W001"不匹配。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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