簡體   English   中英

正則表達式:匹配一種模式並排除另一種模式

[英]Regex: match one pattern and exclude another pattern

我有一個匹配電話號碼的正則表達式:

import re
phones = re.findall(r'[+(]?[0-9][0-9 \-()]{8,}[0-9]', text)

它在大型原始文本數據集中顯示出良好的准確性。

但有時它會匹配不需要的結果(年份范圍和隨機 ID)。

年份范圍:

'2012 - 2017'
'(2011 - 2013'
'1999                                                   02224'
'2019     2010-2015'
'2018-2018 (5'
'2004 -2009'
'1) 2005-2006'
'2011            2020'

隨機ID:

'5                    5                    5                 5'
'100032479008252'
'100006711277302'

我對如何解決這些問題有想法。

  1. 將總位數限制為 12 位。
  2. 將字符總數限制為 16 個字符。
  3. 刪除年份范圍( 19**|20** - 19**|20** )。

但我不知道如何實現這些想法並將它們作為我的正則表達式中的異常。

正則表達式應捕獲的一些示例如下所示:

380-956-425979
+38(097)877-43-88
+38(050) 284-24-20
(097) 261-60-52
380-956-425979
(068)1850063
0975533222

我建議你為不同的電話結構編寫不同的模式。 我不太確定您的電話號碼結構,但這符合您的示例:

import re
test = '''380-956-425979
+38(097)877-43-88
+38(050) 284-24-20
(097) 261-60-52
380-956-425979
(068)1850063
0975533222'''
solution = test.split("\n")

p1 = "\+?\d{3}\-\d{3}\-\d{6}"
p2 = "\+?(?:\d{2})?\(\d{3}\) ?\d{3}\-\d{2}\-\d{2}"
p3 = "\+?\d{3}\-\d{3}\-\d{6}"
p4 = "\+?(?:\(\d{3}\)|\d{3})\d{7}"

result = re.findall(f'{p1}|{p2}|{p3}|{p4}', test)
print(solution)
print(result)

您可以直接在 python 中執行此操作:

if regex.match("condition", "teststring") and not regex.match("not-condition", "teststring"):
   print("Match!")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM