2017-05-29 416 views
1

我需要從excel文件中的列中精確提取7位或8位數字,並且需要丟棄任何數字更多的號碼。正則表達式提取正好8位數字或正好7位數字,如果數字有更多數字,則丟棄

例如,假設這些都是一些的值

2569123659的| > 8位數字以後不提取

2456789 | 2456789 | Extract 7 digit no

15034891 | 15034891 |提取8位數沒有

2569123659 45785612 | 45785612 |僅提取8位數字否

2456789 2569123659 | 2456789 |只提取7位數字沒有

ABC#2456789 | 2456789 |僅提取數字

ABC15034891DSC | 15034891 |僅提取數字

ABC15034891 ### | 15034891 |僅提取數

以下是一些表達式的我試圖

strPattern =「[0-9] {7}([0-9] {1})?「

結果:錯誤的結果

2569123659 | 2456789

2456789 | 15034891

15034891 | 25691236

2569123659 45785612 | 2456789

2456789 2569123659 | 2456789

ABC#2456789 | 2456789

ABC15034891DSC | 15034891

ABC15034891 ### | 15034891

strPattern = 「(\ d {8} | \ d {7})」

結果:仍然是錯誤的結果

2569123659 | 25691236

2456789 | 2456789

15034891 | 15034891

2569123659 45785612 | 25691236

2456789 2569123659 | 2456789

ABC#2456789 | 2456789

ABC15034891DSC | 15034891

ABC15034891 ### | 15034891

幫我修正這個reg表達式,以便處理場景。我只需要提取正確的數字。我需要避免從另一個數字提取更多數字。

任何形式的幫助將不勝感激。預先

由於基於這裏提供的答案


我還試圖

strPattern = 「\ B(\ d {7,8})\ B」

結果仍然錯誤結果

25 69123659 |

2456789 | 2456789

15034891 | 15034891

2569123659 45785612 | 45785612

2456789 2569123659 | 2456789

ABC#2456789 |

ABC15034891DSC |

ABC15034891 ### |

還沒準確

回答

1

使用以下正則表達式:

(?:^|\D)(\d{7,8})(?!\d) 

你的7或8位數字將在.Submatches(0)

(?:^|\D)匹配字符串的開頭或非數字,如果在七位或八位數字後立即找到數字,則否定匹配(?!\d)不匹配。

查看regex demo

看到一個示例代碼:

Sub GetResults() 
Dim rExp As Object, allMatches As Object, match As Object 
Dim text As String 

text = "ABC15034891###" 

Set rExp = CreateObject("vbscript.regexp") 
With rExp 
    .Global = True 
    .MultiLine = False 
    .pattern = "(?:^|\D)(\d{7,8})(?!\d)" 
End With 


Set allMatches = rExp.Execute(text) 
For Each match In allMatches 
    Debug.Print(match.SubMatches.Item(0)) 
Next 

End Sub 
+0

Stribizew謝謝,但不適用於以下情況ABC#2456789 ABC15034891DSC ABC15034891 ### – eccentricCoder

+1

@eccentricCoder [它適用於這些情況](https://regex101.com/r/AuH2zo/1/)。 –

+0

對於上面提到的情況,它返回數字以及附加的#或字母,例如用於ABC#2456789它返回ABC#2456789,對於ABC15034891DSC它返回C15034891並且對於ABC15034891 ###它返回C15034891 – eccentricCoder

1

嘗試\D(\d{7,8})\D

\b -> word boundary 
\d -> digit [0-9] 
\D -> non digit 

演示:https://regex101.com/r/2R5HRN/2

+1

我不知道OP想要抽取從七位號碼'abc1234567def'? –

+2

@Ashraful伊斯蘭非常感謝,這確實解決了我的問題。 – eccentricCoder

+1

@eccentricCoder現在我分組了數字,以便您可以通過'$ 1'訪問它。 –