簡體   English   中英

python 中需要正則表達式幫助

[英]Regular expression help needed in python

誰能幫我形成一個正則表達式來將模式dd-ddd識別為句子中的一個完整單詞,例如在這樣的句子中 -

11-222應該在句首匹配, 33-444在中間但不是55-66-777 ,因為整個單詞不匹配模式。 如果模式出現在末尾,那也應該匹配88-999

如果我使用像'\b\d{2}-\d{3}\b'這樣的正則表達式,它甚至會匹配66-777內的55-66-777 我需要排除它。 不知何故, - (連字符)被視為單詞的邊界。

知道如何實現這一目標嗎?

添加示例代碼和 output

import re
regex_str = r'\b\d{2}-\d{3}\b'
msg_message = '11-222 should be matched, as well as 33-444 but not 55-66-777. If it is present at the end, that should also be matched like 88-999'
for match in re.finditer(regex_str, msg_message):
    print('*'*15)
    print(match.group(0))
    print(match.span())

O/p

***************
11-222
(0, 6)
***************
33-444
(37, 43)
***************
66-777
(55, 61)
***************
88-999
(125, 131)

您可以使用(?<?\S)\d{2}-\d{3}(?!\S) 這種模式確保前后都有一個空白字符(或沒有字符 - 即字符串的開始/結束)。

在此處查看它的使用情況

這個怎么運作:

  • (?<!\S)確保前面的內容不匹配非空白字符
  • \d{2}匹配兩位數
  • -從字面上匹配這個字符
  • \d{3}匹配三位數字
  • (?!\S)確保后面的內容與非空白字符不匹配

雙重否定是故意使用的。 另一種方法是分別使用(?<=\s|^)(?=\s|$) (但它更長,更不性感)。

您可以使用否定的lookbehind來匹配您的模式,但前面沒有連字符

(?<!\-)\d{2}\-\d{3}

import re
regex_str = r'\b(?<!\-)\d{2}\-\d{3}\b'
msg_message = '11-222 should be matched, as well as 33-444 but not 55-66-777. If it is present at the end, that should also be matched like 88-999'
for match in re.finditer(regex_str, msg_message):
    print('*'*15)
    print(match.group(0))
    print(match.span())

***************
11-222
(0, 6)
***************
33-444
(37, 43)
***************
88-999
(125, 131)

如果您想對表達式的右側應用相同的處理,您可以對負前瞻(?!\-)執行相同的操作。

暫無
暫無

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

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