簡體   English   中英

使用正則表達式獲取大寫字母索引

[英]Getting indices of capital letters with regex

我正在嘗試一行獲取大寫字母(包括特殊字母)的索引。 我在這里找到以下解決方案:

[i for i, c in enumerate(s) if c.isupper()]

但是,這不適用於諸如Ö, ÄÜ字母: 在此處輸入圖片說明

因此,我嘗試了:

[re.search(r'^([^A-ZÄÖÜ]*[A-ZÄÖÜ]){i}',s).span()[1] for i in range (1,y)] 

其中y是s中大寫字母的數目。

如果我定義i ,則第二個解決方案有效,但是在循環下,它返回:

attributeerror'nonetype'對象沒有屬性'span'。

如何有效解決問題?

問題是s用字節表示。 它只需要解碼為unicode:

s=u'ÖÄÜ'       # str to unicode
[i for i, c in enumerate(s) if c.isupper()]

Python3:您可以使用isupper()輕松做到這一點,不需要正則表達式。 不幸的是,如果您使用的是Python2.7,這將涉及一些令人討厭的編碼/解碼,而我對此並不熟悉。

x = "HEY thats Some Lower Case ZÄÖÜ"
print([i for i in range(0, len(x)) if x[i].isupper() ])
>[0, 1, 2, 10, 15, 21, 26, 27, 28, 29]

暫無
暫無

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

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