簡體   English   中英

非連字符的正則表達式匹配 - Python

[英]Regex Match for Non Hyphenated Words - Python

我正在嘗試在 Python 中為非連字符單詞創建一個正則表達式,但我無法找出正確的語法。

正則表達式的要求是:

  1. 它不應包含連字符和
  2. 它應該包含至少 1 個數字

我嘗試的表達式是:=

^(?..*-)

  • 這匹配所有非連字符的單詞,但我無法弄清楚如何額外添加第二個條件。

^(?.?*-(,=/d{1,}))

  • 我嘗試使用雙重前瞻,但我不確定要使用的語法。 這匹配ID101但也匹配STACKOVERFLOW

應匹配的示例詞:1DRIVE、ID100、W1RELESS

不應匹配的示例單詞:基本上任何非數字字符串(如 STACK、OVERFLOW)或任何連字符單詞(Test-11、24-hours)

附加信息:

我正在使用庫re並編譯正則表達式模式並使用 re.search 進行匹配。

任何幫助都會非常有幫助,因為我是正則表達式匹配的新手,並且堅持了好幾個小時。

也許,

(?!.*-)(?=.*\d)^.+$

可能只是工作正常。

測試

import re

string = '''
abc
abc1-
abc1
abc-abc1
'''

expression = r'(?m)(?!.*-)(?=.*\d)^.+$'


print(re.findall(expression, string))

Output

['abc1']

如果您想簡化/修改/探索表達式,它已在regex101.com的右上角面板上進行了解釋。 如果您願意,您還可以在此鏈接中觀看它如何與一些示例輸入匹配。


正則表達式電路

jex.im可視化正則表達式:

在此處輸入圖像描述

正則表達式 101 解釋

/
(?!.*-)(?=.*\d)^.+$
/
gm

Negative Lookahead (?!.*-)
Assert that the Regex below does not match
.* matches any character (except for line terminators)
* Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)
- matches the character - literally (case sensitive)
Positive Lookahead (?=.*\d)
Assert that the Regex below matches
.* matches any character (except for line terminators)
* Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)
\d matches a digit (equal to [0-9])
^ asserts position at start of a line
.+ matches any character (except for line terminators)
+ Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)
$ asserts position at the end of a line
Global pattern flags
g modifier: global. All matches (don't return after first match)
m modifier: multi line. Causes ^ and $ to match the begin/end of each line (not only begin/end of string)

我想出了-

^[^-]*\d[^-]*$

  1. 所以我們至少需要一位數字( \d
  2. 我們需要字符串的 rest 包含任何內容,但 a - ( [^-] )
  3. 我們可以有無限數量的這些字符,所以[^-]*
  4. 但是像[^-]*\d那樣將它們放在一起會在aaa3-上失敗,因為 - 出現在有效匹配之后 - 讓我們確保在我們的匹配之前或之后沒有破折號可以潛入^[-]*\d$
  5. 不幸的是,這意味着aaa555D失敗了。 所以我們實際上需要再次添加第一組^[^-]*\d[^-]$ --- 表示開始 - 任意數量的不是破折號的字符 - 一個數字 - 任意數量的字符't dashes - 結束

  6. 根據風格,我們也可以做^([^-]*\d)+$因為數字/數字的順序無關緊要,我們可以擁有任意數量的。

然而,最后......這就是我實際解決這個特定問題的方法,因為正則表達式可能很強大,但它們往往會使代碼更難理解......

if ("-" not in text) and re.search("\d", text):

暫無
暫無

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

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