0

我正在使用此代码

(\d{5})([\-]\d{4})?\s*

哪个符合我的邮政编码

12345-1234

2组

1. 12345
2. -1234

我需要它在 1 个单组中匹配 12345(5 char zip)和 12345-1234(10 char zip)。那可能吗?

编辑:

(\d{5}-\d{4}|\d{5})

(感谢 vcsjones)满足原始问题。

但是,如果 Zip 格式错误(例如 12345-123),它不会仅检索 12345

有没有办法做到这一点?

4

1 回答 1

3

你可以试试这个:

(\d{5}-\d{4}|\d{5})

编辑:

但是,如果 Zip 格式错误(例如 12345-123),它不会仅检索 12345

你确定吗?这会产生一个匹配:

Dim zip5 As String = "12345"
Dim zip9 As String = "12345-6789"
Dim partialZip9 = "12345-33"
Dim regex As New Regex("(\d{5}-\d{4}|\d{5})")
Dim zip5Match = regex.Match(zip5).Groups(0).Value 'Produces 12345
Dim zip9Match = regex.Match(zip9).Groups(0).Value 'Produces 12345-6789
Dim partialZip9Match = regex.Match(partialZip9).Groups(0).Value 'Produces 12345
于 2011-12-28T19:15:04.163 回答