[英]Regex Match for Non Hyphenated Words - Python
我正在嘗試在 Python 中為非連字符單詞創建一個正則表達式,但我無法找出正確的語法。
正則表達式的要求是:
我嘗試的表達式是:=
^(?..*-)
^(?.?*-(,=/d{1,}))
應匹配的示例詞: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))
['abc1']
如果您想簡化/修改/探索表達式,它已在regex101.com的右上角面板上進行了解釋。 如果您願意,您還可以在此鏈接中觀看它如何與一些示例輸入匹配。
jex.im可視化正則表達式:
/
(?!.*-)(?=.*\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[^-]*$
\d
)[^-]
)[^-]*
[^-]*\d
那樣將它們放在一起會在aaa3-
上失敗,因為 - 出現在有效匹配之后 - 讓我們確保在我們的匹配之前或之后沒有破折號可以潛入^[-]*\d$
不幸的是,這意味着aaa555D
失敗了。 所以我們實際上需要再次添加第一組^[^-]*\d[^-]$
--- 表示開始 - 任意數量的不是破折號的字符 - 一個數字 - 任意數量的字符't dashes - 結束
根據風格,我們也可以做^([^-]*\d)+$
因為數字/數字的順序無關緊要,我們可以擁有任意數量的。
然而,最后......這就是我實際解決這個特定問題的方法,因為正則表達式可能很強大,但它們往往會使代碼更難理解......
if ("-" not in text) and re.search("\d", text):
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.